如果远程计算机没有响应,我该如何执行cURL请求并执行给定的操作?
脚本在后台运行,我并不担心让用户等待。
<?php
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'http://example.com/bla.php');
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,array('x'=>'cba!','y'=>'abc'));
if($result = curl_exec($ch)) {
//do this
}
else {
//do this if no response after 5 seconds
}
curl_close($ch);
?>
答案 0 :(得分:1)
使用CURLOPT_CONNECTTIMEOUT和CURLOPT_TIMEOUT
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5); //timeout in seconds