2011-01-22 5 views
1

이제 kannel을 통해 SMS를 보낼 수 있습니다. 그러나 이것은 헤더를 통해 이루어집니다는 예 : 나는 PHP 함수를 통해 SMS를 보내려면 내가 온라인으로 아래의 코드를 가지고 있지만 작동하지 않습니다Php Kannel을 통해 SMS를 보내는 기능

header("Location:http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg"); 

. 뭔가 잘못

function sendSmsMessage($in_number, $in_msg) 
{ 
$url = '/cgi-bin/sendsms?username=' . CONFIG_KANNEL_USER_NAME 
. '&password=' . CONFIG_KANNEL_PASSWORD  
. '&charset=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); 

}

있습니까 : (Kannel의 smsbox 로그에는 요청을 보여줍니다)? CONFIG_KANNEL_USER_NAME을 (를) 대체하고 나머지는 실제 값으로 바꾸려고 시도했지만 여전히 작동하지 않습니다. 제안에 개방.

+0

'echo 'http : //'.CONFIG_KANNEL_HOST.': '.CONFIG_KANNEL_PORT. $ url;'처음으로 요청하려고 시도합니다. – zerkms

답변

4

저는 cURL을 사용했으며 100 % 정상적으로 작동합니다. kannel url에 변수를 전달하기 때문에 file_get_contents가 작동하지 않습니다. file_get_contents가 큰 따옴표 대신에 작은 따옴표 (php는 문자열 값으로 취급합니다)를 사용하는 변수 coz를 처리하지 않기 때문에 php는 문자열 검사를 구문 분석합니다. 변수 등). 여기에 내가 현재 당신의 변수가 어딘가에 이미 초기화되어 있다고 가정하고 있습니다 :

$ 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); 

이것은 kannel에게 숫자에 SMS를 보내라는 간단한 작업을 위해 작동합니다. curl이 공백과 특수 문자를 인식하지 못한다는 것을 깨닫기까지 잠시 시간을 보냈습니다 :-).

+0

컬을 설치하고 cURL을 지원하는 PHP를 실행해야합니다. 리눅스의 경우 sudo를 실행하십시오 - php5-curl을 설치하십시오. phpinfo()를 체크하면 어딘가에 컬이 보일 것입니다. – MaxI

0

사용자를 URL로 리디렉션하지 않고 백그라운드에서 URL 로딩을 시도하는 경우 cURL 또는 심지어 file_get_contents과 같은 것을 사용해야합니다. 당신의 셋업이 URL 래퍼가 활성화 fopen의 경우

예를 들어, 당신은 간단하게 사용할 수 있습니다

$response = file_get_contents("http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg"); 

에 관계없이, 당신이 볼 수있는 기능이 몇 가지 추가 디버그 정보없이 작동하지 않습니다 이유를 알고 어렵다. CONFIG_KANNEL_HOST가 "localhost"로 정의되고 CONFIG_KANNEL_PORT가 13013으로 정의 된 경우 추가 문자 집합 연산을 사용하더라도 효과가 동일합니다.

+0

그 file_get_contents는 $ in_number를 문자열 대신에 $ in_number 변하기 쉬운. 큰 따옴표는 변수 문제를 해결하지만 file_get_contents()는 작은 따옴표로 정의 된 문자열을 필요로합니다. 직접 문자열에 변수를 전달하는 방법이 있습니까? thanks – MaxI

+0

@Max file_get_contents는 작은 따옴표가있는 문자열을 필요로하지 않습니다. 작은 따옴표와 큰 따옴표는 PHP에서 단일 구조 내에서 일관되게 사용되는 한 바꿔 쓸 수 있습니다. (이중 인용 부호가 다른 모든 임베디드 변수를 평가할 것입니다.) 따라서 작은 따옴표를 큰 따옴표로 바꾸면 모든 것이 잘되어야합니다. :-) –

+0

나를 믿어 라. 교환 할 수 없습니다. 난 노력 했어. cURL을 사용하려고 시도 – MaxI

1

내 친구이자 Ndola, Zambia에서 kuran_1.4.3을 실행하기 위해 우분투 11.04를 사용하고 있습니다. 그것은 sms를 보내고받을 때 완벽하게 작동합니다. 아래 코드는 70 자 이상을 보내려면 편집해야했습니다. 제 친구와 저는 '& charset = UCS-2 & coding = 2'이라는 줄에 작은 오류가 있음을 알아 내려고 애썼다. 올바른 행은 '& charset = UCS-2 & 인코딩 = 2'이어야합니다. 그래서 코드는 다음과 같이 나타납니다 :

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)); 
+0

저는 케냐 출신이고 우분투 10.04.3을 사용합니다. 나는이 기능을 확실히 시험해 볼 것입니다. – MaxI

1

컬 사용 : 등

$gw_host=127.0.0.1 
$gw_port=13xx3 

: 같은 당신의 가치와 다양한 변수/매개 변수를 교체

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"); 

0

고대 질문을 ressucitate하지 않기,하지만 같은 일을 찾고 후예 및 다른 사람을 위해 :

[[email protected] 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 == ""; 

    } 

    ?> 

그리고 당신은 SMS를 수신이 다른 하나를 가지고 그것을 저장할 수에 mysql을 :

[[email protected] 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"; 
    } 

    ?> 

이 문자 메시지는 SMS 수신자 및 SMS 배달 알림 수신자 (SMS 수신자가 수신되었음을 확인하기 위해 거기에 놓인 데이터베이스의 레코드를 업데이트 함)를 겸합니다.

SMS를 보낼 때 DLR에 URL을 보내고 (확인을 요청하는 DLR 마스크를 설정하기 때문에) DLR에 사용되지만 인바운드 SMS의 경우에는 kannel.conf를 사용하도록 구성해야합니다. SMS 서비스는,이 포괄 하나의 단지 예 : 포르투갈어에서 일부 텍스트에 대한

[...] 
    group = sms-service 
    keyword = default 
    get-url = "http://localhost/tools/kannel-receive.php?type=inbsms&text=%a&timesent=%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 
    [...] 

미안하지만, 당신이 사진을 얻을 수 있습니다

0

// PHP 코드 파일 이름이 TEST2입니다.. php.before, 우분투 14에 php5-curl을 설치해야합니다.