Codeigniter - 如何通过URL发送API数据并立即获得响应,而无需重定向和表单操作

时间:2014-07-01 02:10:44

标签: php xml api codeigniter sms-gateway

以下是我的代码:

$sourceaddr = 14045; // Sender ID
$destinationaddr = 08887654657; // Destination Address
$shortmessage = "Hi, this is test"; // Message
$url = http://xyz.li/cdk; //Short URL

我通过以下URL(由SMS Broadcast API提供)发送上述数据

// API for sending SMS
$sent_url = 'http://username:password@ip:port/smsgateway/infobulk?sourceaddr='.$sourceaddr.'&destinationaddr='.$destinationaddr.'&shortmessage='.urlencode($shortmessage).' '.urlencode($url).'';

如果按目的地地址收到(成功)消息,我将收到此回复:

<?xml version="1.0" encoding="iso-8859-1" ?>
<message>
<TrxID>13349105571516524200</TrxID>
<Status>SENT</Status>
</message>

如何以Codeigniter的方式做到这一点?

我尝试使用redirect($sent_url),但没有得到任何回复, 这是一个后端进程,所以我不需要任何表单操作,谢谢。

1 个答案:

答案 0 :(得分:2)

模型

class Sms_model extends CI_Model {

  var $source; //Source address
  var $dest; //Destination
  var $msg; // Message
  var $url;
  var $api_url;


  function __construct() {
    parent::__construct();
  }

  function Send(){

    $this->api_url = 'http://username:password@ip:port/smsgateway/infobulk';
    $params = $this->source.'&destinationaddr='.$this>dest.'&shortmessage='.urlencode($this->msg).' '.urlencode($this->url).'';

    $post_data = array(
        "sourceaddr" => $params,
    );

    $stream_options = array(
        'http' => array(
           'method'  => 'POST',
        ),
    );

    $context  = stream_context_create($stream_options);
    $response = file_get_contents($this->api_url, null, $context);

    return $response;
 }
}

CONTROLLER

class Sms extends CI_Controller {

  function __construct() {
    parent::__construct();
  }

  function Index(){
    $this->load->model('Sms_model','sms_m');

    $this->sms_m->source = 14045 ;
    $this->sms_m->dest = 08887654657;
    $this->sms_m->msg = "Hi, this is test";
    $this->sms_m->url = 'http://xyz.li/cdk';

    $data = $this->sms_m->Send();

    print_r($data); 

   }
}

这适用于CI。欢呼声。