原文:http://phpquan.com/lamp/php/php-curl-timeout/
网站登录不了,原因是没有可用的 PHP 子进程来响应新的请求了。这可能是是由于PHP-curl 没有设置超时时间引起的。
php使用curl设置超时的重要性
这段时间用PHP写了个爬虫程序,但是经常执行了一段时间后程序就卡住了。
程序是用的curl方式进行抓取,后来设置了 CURLOPT_TIMEOUT 参数就没有出现这个问题了
平常如果测试curl都直接设置了url就直接执行了。
curl功能还是很强大的,如果线上使用最好还是把 所有参数都设置一遍,还可以设置毫秒级超时
最后分享一段 curl 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
function
http_request(
$URI
,
$isHearder
= false,
$post
= false)
{
$ch
= curl_init();
curl_setopt(
$ch
, CURLOPT_URL,
$URI
);
curl_setopt(
$ch
, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
$ch
, CURLOPT_TIMEOUT, 60);
//单位 秒,也可以使用
#curl_setopt(
$ch
, CURLOPT_NOSIGNAL, 1);
//注意,毫秒超时一定要设置这个
#curl_setopt(
$ch
, CURLOPT_TIMEOUT_MS, 200);
//超时毫秒,cURL 7.16.2中被加入。从PHP 5.2.3起可使用
curl_setopt(
$ch
, CURLOPT_HEADER,
$isHearder
);
curl_setopt(
$ch
, CURLOPT_USERAGENT,
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36'
);
curl_setopt(
$ch
, CURLOPT_COOKIEFILE, dirname(
__FILE__
).
"/tmp.cookie"
);
curl_setopt(
$ch
, CURLOPT_COOKIEJAR, dirname(
__FILE__
).
"/tmp.cookie"
);
if
(
strpos
(
$URI
,
'https'
) === 0){
curl_setopt(
$ch
, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt(
$ch
, CURLOPT_SSL_VERIFYHOST, FALSE);
}
if
(
$post
){
curl_setopt (
$ch
, CURLOPT_POST, 1);
curl_setopt (
$ch
, CURLOPT_POSTFIELDS,
$post
);
}
$result
= curl_exec(
$ch
);
curl_close(
$ch
);
return
$result
;
|