简体   繁体   English

cURL - 使用 PHP 发送 GET 请求

[英]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. curl_getinfo返回 0, $output返回任何内容,但文档说如果请求成功,则$output为 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:根据您的最终评论,由于问题是由于未对 URL 参数进行 url 编码造成的,因此我认为最简单的方法是这样的:

$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.有关更多信息,请参阅http_build_query() It will safely encode the array into a string suitable for URL encoded HTTP POST requests, or for query string parameters.它将安全地将数组编码为适合 URL 编码的 HTTP POST 请求或查询字符串参数的字符串。

When a cURL request fails, seeing everything returned by curl_getinfo() is helpful too.cURL请求失败时,查看curl_getinfo()返回的所有内容也很有帮助。

In this case I would have thought the HTTP code would have been 400 , for bad request.在这种情况下,我会认为HTTP代码是400 ,对于错误的请求。 Also you call do echo curl_error($ch);你也叫 do echo curl_error($ch); for a human-readable error message.用于人类可读的错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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