dongyang2229 2013-04-26 04:37
浏览 43
已采纳

使用HTTP Get请求的PHP URL编码

I've set up a PHP script to send a text message using the Nexmo API, however there's a problem with how I'm encoding the HTTP Get request. The script pulls some variables from stored data, and then fires. I'm not experienced with PHP and have spent so much time on this already, this is my last resort, is anyone able to see where I've gone wrong in the following code?

The intended format for the request:

https://rest.nexmo.com/sms/json?api_key=XXX&api_secret=XXX&to=XXX&from=XXX&text=XXX

The code:

function sendText () {

    $api_key = $settings['consumer_key'];
    $api_secret = $settings['consumer_secret'];
    $recipient = $settings['recipient'];
    $from = $settings['from'];
    $text = $settings['sms_contents'];

    $url = 'https://rest.nexmo.com/sms/json';
    $data = array_merge($data, array('api_key' => $api_key, 'api_secret' => $api_secret, 'to' => $recipient, 'from' => $from, 'text' => $text));

    $post = '';
    foreach($data as $k => $v){
        $post .= "&$k=$v";
    }

    $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $post
            )
        );
    $context = stream_context_create($opts);
    $from_nexmo = file_get_contents($url, false, $context);

    }

sendText();
  • 写回答

3条回答 默认 最新

  • doulu7174 2013-04-26 04:41
    关注

    Try to use urlencode() for transfered values:

    $post = array();
    
    foreach($data as $k => $v){
        $post[] = $k . '=' . urlencode($v);
    }
    
    $post = implode('&', $post);
    
    $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $post
            )
        );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?