Php Function to send SMS via Kannel
I can now send an SMS via kannel. However this is done via headers eg:
header("Location:http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg");
I want to send an sms via a php function and I got the code below online but it doesn't work. (Kannel smsbox log shows no request):
function sendSmsMessage($in_number, $in_msg)
{
$url = '/cgi-bin/sendsms?username=' . CONFIG_KANNEL_USER_NAME
. '&password=' . CONFIG_KANNEL_PASSWORD
. '&开发者_如何学JAVAcharset=UCS-2&coding=2'
. "&to={$in_number}"
. '&text=' . urlencode(iconv('utf-8', 'ucs-2', $in_msg));
$results = file('http://'
. CONFIG_KANNEL_HOST . ':'
. CONFIG_KANNEL_PORT . $url);
}
Is there something wrong? I tried replacing the CONFIG_KANNEL_USER_NAME and the rest with the actual values but it still doesn't work. Open to suggestions.
I used cURL and it works 100% okay. file_get_contents does not work for me because I want to pass variables to the kannel url and file_get_contents does not process variables coz it insists on using single quotes(php treats it as a string value) instead of double quotes(php will parse the string checking for variables etc). Here is what i am currently doing assuming you already have your variables initialized somewhere:
$textmsg="Hello Stackoverflow Users!";
$cellphone_number = "+254xxxxxxx"
$encmsg=urlencode($textmsg);
$ch= curl_init();
curl_setopt($ch, "http://localhost:13013/cgi-bin/sendsms?username=xxxxx&password=xxxxx&to=$cellphone_number&text=$encmsg");
curl_exec($ch);
curl_close($ch);
This will work for the simple task of telling kannel to send an sms to a number. Took me a while to realize curl does not recognize spaces and special characters :-).
My friend and I from Ndola, Zambia are using ubuntu 11.04 to run kannel_1.4.3. It works perfectly way in sending and receiving sms. The code below had to be edited for it to send more that 70 characters. My friend and I struggled to figure out that there was a small error in the line '&charset=UCS-2&coding=2'. The correct line should be '&charset=UCS-2&encoding=2'. So the code should appear as below:
function sendSmsMessage($in_number, $in_msg)
{
$url = '/cgi-bin/sendsms?username=' . CONFIG_KANNEL_USER_NAME
. '&password=' . CONFIG_KANNEL_PASSWORD
. '&charset=UCS-2&encoding=2'
. "&to={$in_number}"
. '&text=' . urlencode(iconv('utf-8', 'ucs-2', $in_msg));
Using curl:
curl_init("http://$gw_host:$gw_port/cgi-bin/sendsms?username=$gw_user&password=$gw_pass&to=$to&from=$shortcode&smsc=$smsc&dlr-mask=$dlrmask&binfo=$shortcode&text=$message");
Replace the various variables/parameters with your values such as:
$gw_host=127.0.0.1
$gw_port=13xx3
etc.
If you're attempting to trigger a URL loading in the background (rather than by re-directing the user to the URL), you need to use something like cURL or perhaps even file_get_contents.
For example, if your set up has fopen URL wrappers enabled, you could simply use:
$response = file_get_contents("http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg");
Irrespective, it's hard to know why the function you found won't work without some additional debug information. (If CONFIG_KANNEL_HOST is defined as "localhost" and CONFIG_KANNEL_PORT is defined as 13013 then it's effectively doing the same thing, albeit with additional character set operations.)
Not to ressucitate an ancient question, but for posteriority and others searching for the same thing:
[root@sat2 tools]# cat kannel-send.php
<?php
function send_sms($msgid, $numto, $msgtext, $smsc = "smsc-default", $dlrmask = 63)
{
$sendsmsurl_prefix = "http://localhost:13013/cgi-bin/sendsms";
$dlrurl_prefix = "http://localhost/tools/kannel-receive.php";
$username = "user";
$password = "pass";
# fix number to what carriers expect
$numto = preg_replace('/^0/', '', $numto);
$numto = preg_replace('/^\+55/', '', $numto);
$numto = "0" . $numto;
if (!$msgid) $dlrmask = 0;
$dlrurl_params = array(
"type" => "dlr",
"timesent" => "%t",
"smsc" => "%i",
"uuid" => "%I",
"fid" => "%F",
"dlr-cod" => "%d",
"reply" => "%A",
"msgid" => $msgid,
"text" => "%a",
"to" => "%P",
"from" => "%p",
"origsmsc" => "%f",
);
$dlrurl = $dlrurl_prefix . "?" . urldecode(http_build_query($dlrurl_params));
$sendsmsurl_params = array(
"username" => $username,
"password" => $password,
"to" => $numto,
"dlr-mask" => $dlrmask,
"dlr-url" => $dlrurl,
"smsc"=> $smsc,
"text" => $msgtext,
);
$sendsmsurl = $sendsmsurl_prefix . "?" . http_build_query($sendsmsurl_params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $sendsmsurl);
$bogus = curl_exec($ch);
$ret = curl_error($ch);
curl_close($ch);
return $ret == "";
}
?>
And you could have this other one to receive sms and store it to mysql:
[root@sat2 tools]# cat kannel-receive.php
<?php
$debug = false;
$link = null;
function dbconnect()
{
global $link, $debug;
if ($link && mysql_ping($link))
return;
if ($debug) echo "Conectando ao banco de dados\n";
// TODO: criar um usuario de banco especifico pra isso
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'dbname';
$link = mysql_connect($host, $user, $pass, true);
if (!$link){
if ($debug) echo "Can't connect to mysql: " . mysql_error() . "\n";
} else {
mysql_select_db($db, $link);
}
return;
}
function esc($str)
{
global $link;
return mysql_real_escape_string($str, $link);
}
if ($debug) {
echo "<br>Kannel inbound sms event:<br>\n";
var_dump($_GET);
}
dbconnect();
if ($_GET['type'] == "inbsms") {
$_GET['from'] = preg_replace('/^(\+55|0)/', '', $_GET['from']);
$sql = "INSERT INTO notificacao (tipo, endereco, mensagem, device,
dataEvento, situacao)
VALUES ('%s', '%s','%s','%s','%s','%s')";
$sql = sprintf($sql, 'sms', esc($_GET['from']), esc($_GET['text']),
esc($_GET['smsc']), esc($_GET['timesent']), "received");
} elseif ($_GET['type'] == "dlr") {
switch (esc($_GET['dlr-cod'])) {
case "1":
$sql = "UPDATE notificacao SET
situacao = 'confirmed',
dataConfirmacao = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
case "8":
$sql = "UPDATE notificacao SET
situacao = 'sent',
device = '{$_GET['smsc']}',
dataEvento = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
case "16":
$sql = "UPDATE notificacao SET
situacao = 'failed',
device = '{$_GET['smsc']}',
razaofalha = '{$_GET['reply']}',
dataEvento = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
}
}
if ($debug) echo "sql: $sql\n";
$result = mysql_query($sql, $link);
if (!$result) {
if ($debug) echo "Erro sql: " . mysql_error() . "\n";
}
?>
This one doubles as a SMS receiver and a SMS-Delivery-Notification receiver (in that case it updates a record on the database that was put there when sending the sms, to confirm it was received).
It's used for DLR because I send the URL for that when sending the SMS (and set the DLR mask asking for confirmation), but for inbound SMS you have to configure your kannel.conf to use it (you can have many sms-service, this is just an example of a catch-all one:
[...]
group = sms-service
keyword = default
get-url = "http://localhost/tools/kannel-receive.php?type=inbsms&text=%a×ent=%t&from=%p&to=%P&smsc=%i&uuid=%I&delivery=%d&service=%n&encoding=%c&class=%m&mwi=%M&charset=%C&udh=%u&dcs=%O&origsmsc=%f"
catch-all = yes
max-messages = 0
accept-x-kannel-headers = true
concatenation = yes
omit-empty = yes
[...]
Sorry for some texts in portuguese, but you can get the picture.
//php code file name is test2.php.before that,you must install php5-curl on ubuntu14
精彩评论