如何使用 curl 在 php 中调试 get 请求

2022-01-04 00:00:00 debugging rest get curl php

我正在尝试使用 curl 在 php 中发出一个 get 请求.这就是我正在做的:

I'm trying to make a get request in php using curl. This is what I'm doing:

$curl = curl_init();

curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($curl);
curl_close($curl);

printf($result);

但是 $result 不打印任何内容,没有成功或失败的消息.我已经通过邮递员和网络浏览器成功到达端点,所以我知道它可以工作.打印 $curl 打印:"Resource #1" 这让我认为 curl 已正确安装在服务器上.

But $result doesn't print out anything, no success or failure message. I've successfully reached the endpoint via postman and in a web browser so I know it works. Printing out $curl prints: "Resource #1" which makes me think curl is properly installed on the server.

我不确定接下来要采取什么步骤来使事情顺利进行.

I'm not sure what steps to take next to make things work.

推荐答案

添加更多选项以进行故障排除.

Add a few more option for troubleshooting purposes.

检查错误响应.

如果没有错误,获取详细信息:

If no error, get the details:

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
curl_setopt($ch, CURLOPT_FAILONERROR,true);
curl_setopt($ch, CURLOPT_ENCODING,"");

curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HEADER, true);

$data = curl_exec($ch);
if (curl_errno($ch)){
    $data .= 'Retreive Base Page Error: ' . curl_error($ch);
}
else {
  $skip = intval(curl_getinfo($ch, CURLINFO_HEADER_SIZE)); 
  $head = substr($data,0,$skip);
  $data = substr($data,$skip);
  $info = curl_getinfo($ch);
  $info = var_export($info,true);
}
echo $head;
echo $info;

相关文章