PHP常用代碼 —— 發送 SMS

在開發 Web 或者移動應用的時候,經常會遇到需要發送 SMS 給用戶,或者因爲登錄原因,或者是爲了發送信息。下面的 PHP 代碼就實現了發送 SMS 的功能。
爲了使用任何的語言發送 SMS,需要一個 SMS gateway。大部分的 SMS 會提供一個 API,這裏是使用 MSG91 作爲 SMS gateway。

function send_sms($mobile,$msg)
{
	$authKey = "XXXXXXXXXXX";
	date_default_timezone_set("Asia/Kolkata");
	$date = strftime("%Y-%m-%d %H:%M:%S");
	//Multiple mobiles numbers separated by comma
	$mobileNumber = $mobile;
	           
	//Sender ID,While using route4 sender id should be 6 characters long.
	$senderId = "IKOONK";
	           
	//Your message to send, Add URL encoding here.
	$message = urlencode($msg);
	           
	//Define route 
	$route = "template";
	//Prepare you post parameters
	$postData = array(
	    'authkey' => $authKey,
	    'mobiles' => $mobileNumber,
	    'message' => $message,
	    'sender' => $senderId,
	    'route' => $route
	);
	           
	//API URL
	$url="https://control.msg91.com/sendhttp.php";
	           
	// init the resource
	$ch = curl_init();
	curl_setopt_array($ch, array(
	    CURLOPT_URL => $url,
	    CURLOPT_RETURNTRANSFER => true,
	    CURLOPT_POST => true,
	    CURLOPT_POSTFIELDS => $postData
	    //,CURLOPT_FOLLOWLOCATION => true
	));
	           
	           
	//Ignore SSL certificate verification
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	           
	           
	//get response
	$output = curl_exec($ch);
	//Print error if any
	if(curl_errno($ch))
	{
	    echo 'error:' . curl_error($ch);
	}
	           
	curl_close($ch);
}

$authKey :需要你輸入你的密碼
$senderId : 需要你輸入你的 SenderID
當輸入移動號碼的時候需要指定國家代碼 (比如,美國是 1,印度是 91 )

語法:

<?php
$message = "Hello World";
$mobile = "918112998787";
send_sms($mobile,$message);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章