如何在 PHP 中捕获 cURL 错误 [英] How to catch cURL errors in PHP

查看:38
本文介绍了如何在 PHP 中捕获 cURL 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PHP curl 函数从我的本地机器将数据发布到 Web 服务器.我的代码如下:

I am using PHP curl functions to post data to the web server from my local machine. My code is as follows:

$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($c);
if (curl_exec($c) === false) {
    echo "ok";
} else {
    echo "error";
}
curl_close($c);

很遗憾,我无法捕捉到任何错误,例如 404、500 或网络故障.那么我如何才能知道数据没有发布到远程或从远程检索?

Unfortunately I am not able to catch any errors like 404, 500 or network failure. So how will I get to know that data was not posted to or retrieved from the remote?

推荐答案

您可以使用 curl_error() 函数来检测是否有错误.例如:

You can use the curl_error() function to detect if there was some error. For example:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $your_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true); // Required for HTTP error codes to be reported via our call to curl_error($ch)
//...
curl_exec($ch);
if (curl_errno($ch)) {
    $error_msg = curl_error($ch);
}
curl_close($ch);

if (isset($error_msg)) {
    // TODO - Handle cURL error accordingly
}

在这里查看libcurl错误代码的说明

此处查看 PHP curl_errno() 函数说明

此处查看 PHP curl_error() 函数说明

这篇关于如何在 PHP 中捕获 cURL 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆