在工作中经常需要用到curl请求,得到返回值做出相应的处理,还可能需要记录日志。
下面是模拟下curl的请求操作,我们一共需要2个文件。我们可以在response.php文件里做两个操作,一个操作是模拟请求超时和返回500错误(关闭PHP报错,display_error改成off)
request.php
$url = "http://localhost/abc/response.php";
$ch = curl_init ();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$data = curl_exec($ch);
$info = curl_getinfo($ch);
$status = 1;
if (curl_error($ch)) {
$status = -1;
$error_msg = curl_errno($ch);//获取错误返回码
}
//关闭URL请求
curl_close($curl);
//显示获得的数据
$result['status']=$status;
$result['msg'] = empty($error_msg)? '请求成功':"请求失败,状态码".$error_msg;
$result['data']['data']=$data;
$result['data']['info']=$info;
$result['data']['error_info']=$error_msg;
var_dump($result);
response.php
<?php
sleep(6);//sleep时间大于CURLOPT_TIMEOUT的超时时间
echo "1212";//这边可以把分号删除,看看500报错,最后的打印结果是什么
上述代码肯定是请求超时了,我们试试看返回值是什么!
Array
(
[status] => -1
[msg] => 请求失败,状态码28
[data] => Array
(
[data] =>
[info] => Array
(
[url] => http://localhost/abc/response.php
[content_type] =>
[http_code] => 0
[header_size] => 0
[request_size] => 64
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 3
[namelookup_time] => 1.0E-6
[connect_time] => 0.016
[pretransfer_time] => 0.016
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => -1
[upload_content_length] => -1
[starttransfer_time] => 0
[redirect_time] => 0
[redirect_url] =>
[primary_ip] => 127.0.0.1
[certinfo] => Array
(
)
[primary_port] => 80
[local_ip] => 127.0.0.1
[local_port] => 51516
)
[error_info] => 28
)
)
curl_getinfo返回参数
url:网络地址。
content_type:内容编码。
http_code:HTTP状态码。
header_size:header的大小。
request_size:请求的大小。
filetime:文件创建的时间。
ssl_verify_result:SSL验证结果。
redirect_count:跳转计数。
total_time:总耗时。
namelookup_time:DNS查询耗时。
connect_time:等待连接耗时。
pretransfer_time:传输前准备耗时。
size_uplpad:上传数据的大小。
size_download:下载数据的大小。
speed_download:下载速度。
speed_upload:上传速度。
download_content_length:下载内容的长度。
upload_content_length:上传内容的长度。
starttransfer_time:开始传输的时间表。
redirect_time:重定向耗时。