使用HTTP Get请求的PHP URL编码

时间:2013-04-26 04:37:29

标签: php url-encoding

我已经设置了一个PHP脚本来使用Nexmo API发送短信,但是我对HTTP Get请求的编码方式存在问题。该脚本从存储的数据中提取一些变量,然后触发。我对PHP没有经验,并且已经花了这么多时间在这上面,这是我的最后一招,是否有人能够在下面的代码中看到我出错的地方?

请求的预期格式:

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

代码:

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 个答案:

答案 0 :(得分:1)

我不认为你在做任何编码,这就是我要做的事情:

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

答案 1 :(得分:0)

尝试将urlencode()用于传输值:

$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 :(得分:0)

Please try executing following code snippet

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=http_build_query($data);

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