简体   繁体   中英

cURL - sending GET request using PHP

I can't understand where i am doing wrong.

below is my code:

$message = "testing from the application.";
$mobile_number = ""; //hidden for security
$sender = ""; //hidden for security    
$ch = curl_init(""); //hidden for security, http://ip
curl_setopt($ch, CURLOPT_URL, "api.php?username=&password=&number=$mobile_number&sender=$sender&type=0&message=$message");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
echo $output = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

curl_getinfo return 0, and $output did't return anything, but the Document says if the request successful then the $output is 1101.

I tested it in the postman, the result is ok.

Based on your final comment, since the problem was due to the URL parameters not being url encoded, the simplest way to do so I think is like this:

$params = array(
    'message'  => "testing from the application.",
    'number'   => "", //hidden
    'sender'   => "", //hidden
    'username' => $username,
    'password' => $password,
    'type'     => 0,
);

$url = 'api.php?'. http_build_query($params);

curl_setopt($ch, CURLOPT_URL, $url);

See http_build_query() for more information. It will safely encode the array into a string suitable for URL encoded HTTP POST requests, or for query string parameters.

When a cURL request fails, seeing everything returned by curl_getinfo() is helpful too.

In this case I would have thought the HTTP code would have been 400 , for bad request. Also you call do echo curl_error($ch); for a human-readable error message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM