我正在使用PHP curl
functions将数据从我的本地计算机发送到web服务器。我的代码如下:
$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或网络故障。那么,我如何才能知道数据没有发送到遥控器或从遥控器检索?
发布于 2010-10-21 19:43:53
您可以使用curl_error()
函数来检测是否存在错误。例如:
$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
}
See the description of libcurl error codes here
发布于 2014-04-18 00:41:43
如果CURLOPT_FAILONERROR
为false
,则http错误不会触发curl
错误。
<?php
if (@$_GET['curl']=="yes") {
header('HTTP/1.1 503 Service Temporarily Unavailable');
} else {
$ch=curl_init($url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."?curl=yes");
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$response=curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errno= curl_errno($ch);
if ($http_status==503)
echo "HTTP Status == 503 <br/>";
echo "Curl Errno returned $curl_errno <br/>";
}
发布于 2018-07-18 23:03:14
由于您对捕获网络相关错误和HTTP错误感兴趣,因此下面提供了一种更好的方法:
function curl_error_test($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$responseBody = curl_exec($ch);
/*
* if curl_exec failed then
* $responseBody is false
* curl_errno() returns non-zero number
* curl_error() returns non-empty string
* which one to use is up too you
*/
if ($responseBody === false) {
return "CURL Error: " . curl_error($ch);
}
$responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
/*
* 4xx status codes are client errors
* 5xx status codes are server errors
*/
if ($responseCode >= 400) {
return "HTTP Error: " . $responseCode;
}
return "No CURL or HTTP Error";
}
测试:
curl_error_test("http://expamle.com"); // CURL Error: Could not resolve host: expamle.com
curl_error_test("http://example.com/whatever"); // HTTP Error: 404
curl_error_test("http://example.com"); // No CURL or HTTP Error
https://stackoverflow.com/questions/3987006
复制相似问题