如果cURL请求没有响应,执行给定的PHP任务


Perform given PHP task if no response from cURL request

如果远程机器没有响应,我如何执行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);
?>

使用CURLOPT_CONNECTTIMEOUT和CURLOPT_TIMEOUT

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5); 
curl_setopt($ch, CURLOPT_TIMEOUT, 5); //timeout in seconds