Vitali
Vitali

Reputation: 95

GET request via CURL in PHP

I have CURL script as below:

$url= 'https://www.test.com/test.php';
$msg=?p1={1250.feed}&p2={jt2221}&p3={1330}&p4={1234567890}&p5={2016-02-04 20:05:34}&p6={New York}; 

$url .= $msg;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
}
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

var_dump($http_status);
var_dump($result);

the full string url and message , when I copy/past on Chrome web browser the remote PHP file receives well. When same url+message sent by PHP script not works. I guess the problem is first the remote domain is HTTPS , second seems curly brackets and space disturbs the CURL request.I tried urlencode($msg) function then got Error 404 . On success sent message , remote PHP returns {"Code":null,"Msg":"."} as ACK

Upvotes: 2

Views: 19238

Answers (1)

John C
John C

Reputation: 8415

If you are using urlencode, you'll just want to encode the values, not the whole query string. An efficient way to do this (and keep your query data in neat arrays) is with http_build_query:

$url= 'https://www.test.com/test.php?';

$data = array('p1' => '{1250.feed}',
              'p2' => '{jt2221}',
              'p3' => '{1330}',
              'p4' => '{1234567890}',
              'p5' => '{2016-02-04 20:05:34}',
              'p6' => '{New York}',);

$msg = http_build_query($data);

$url .= $msg;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
}
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

var_dump($http_status);
var_dump($result);

Upvotes: 2

Related Questions