这段时间用PHP写了个爬虫程序,可是常常执行了一段时间后程序就卡住了。
程序是用的curl方式进行抓取,后来设置了 CURLOPT_TIMEOUT 参数就没有出现这个问题了
日常若是测试curl都直接设置了url就直接执行了。
curl功能仍是很强大的,若是线上使用最好仍是把 全部参数都设置一遍,还能够设置毫秒级超时
最后分享一段 curl 方法post
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
;
|