If you want to fetch the error message, make sure you fetch it before you close the current cURL session or the error message will be reset to an empty string.
PHP - Manual: curl_error
2024-12-22
(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)
curl_error — 返回当前会话最后一次错误的字符串
$ch
): string返回最近一次 cURL 操作的文本错误详情。
返回错误信息,或者如果没有任何错误发生就返回 ''
(空字符串)。
示例 #1 curl_error() 例子
<?php
// 创建 cURL 句柄,指向一个不存在的位置
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo '操作完成没有任何错误';
}
// 关闭句柄
curl_close($ch);
?>
If you want to fetch the error message, make sure you fetch it before you close the current cURL session or the error message will be reset to an empty string.
For a 404 response to actually trigger an error as the example seems to be trying to demonstrate the following option should be set:
curl_setopt($ch,CURLOPT_FAILONERROR,true);
As per http://curl.haxx.se/libcurl/c/libcurl-errors.html
CURLE_HTTP_RETURNED_ERROR (22)
This is returned if CURLOPT_FAILONERROR is set TRUE and the HTTP server returns an error code that is >= 400. (This error code was formerly known as CURLE_HTTP_NOT_FOUND.)
If you're using curl_multi and there's an error, curl_error() will remain empty until you've called curl_multi_info_read(). That function "pumps" the information inside the curl libraries to the point where curl_error() will return a useful string.
This should really be added to the documentation, because it's not at all obvious.
curl_error is not a textual representation of curl_errno.
It's an actual error *message*.
If you want textual representation of error *code*, look for curl_strerror.