douhanzhen8927 2016-06-08 10:24
浏览 55

如何处理PHP cURL的错误

I've done every bit of tips and answers but I can't seem to find the right solution.

my cURL is as follows

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $curlIP."api/sparts/search/");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, "key=".$q."&page=".$pg);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

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

What does this do?

It gets products data from a server where $q is the search key and $pg is the page number

This cURL works as intended assuming the server will always have an internet connection. As the developer we needed to have an error message whenever the cURL cannot connect to the server.

What is the problem?

For me to actually set an error message I need to know first if the error has happened. This where it gets weird for me. I tried to simulate connection failure by disabling the internet adapter of the server.

The result is:

the page stops parsing everything after the $data = curl_exec($curl);This includes the footer and everything after that line. I knew it because I tried to put echoes before and after curl_exec and it really stops there. therefore I cannot catch the error itself.

What have I tried?

I tried

  • PHP curl_error() - which didn't really help since the script stops at curl_exec
  • PHP curl_errno() - same
  • try and catch - This should have catch the error but it didn't which frustrates me even more.
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 WPF 大屏看板表格背景图片设置
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭
    • ¥15 2020长安杯与连接网探
    • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
    • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
    • ¥16 mybatis的代理对象无法通过@Autowired装填
    • ¥15 可见光定位matlab仿真
    • ¥15 arduino 四自由度机械臂
    • ¥15 wordpress 产品图片 GIF 没法显示