Reputation: 439
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();
Upvotes: 0
Views: 2306
Reputation: 3845
Please try executing the 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();
Upvotes: 0
Reputation: 43850
I don’t think you are doing any encoding. Here is what I would do:
foreach($data as $k => $v){
$post .= "&$k=" . urlencode($v);
}
Upvotes: 1
Reputation: 12168
Try to use urlencode()
for transferred 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
)
);
Upvotes: 0