1、file_get_contents 请求超时设置
1 2 3 4 5 6 7
| $timeout = array( 'http'=> array( 'timeout'=>5//设置一个超时时间,单位为秒 ) ); $ctx = stream_context_create($timeout); $text = file_get_contents("https://www.leixuesong.com/",0, $ctx); |
2、fopen 请求超时设置
1 2 3 4 5 6 7 8 9 10 11 12
| $timeout = array( 'http' => array( 'timeout' => 5 //设置一个超时时间,单位为秒 ) ); $ctx = stream_context_create($timeout); if ($fp = fopen("https://www.leixuesong.com/", "r", false, $ctx)) { while( $c = fread($fp, 8192)) { echo $c; } fclose($fp); } |
3、curl请求超时设置
CURL 是常用的访问HTTP协议接口的lib库,性能高,还有一些并发支持的功能等。
curl_setopt($ch, opt) 可以设置一些超时的设置,主要包括:a 、CURLOPT_TIMEOUT 设置cURL允许执行的最长秒数。b、CURLOPT_TIMEOUT_MS 设置cURL允许执行的最长毫秒数。c、 CURLOPT_CONNECTTIMEOUT 在发起连接前等待的时间,如果设置为0,则无限等待。d、 CURLOPT_CONNECTTIMEOUT_MS 尝试连接等待的时间,以毫秒为单位。如果设置为0,则无限等待。e、 CURLOPT_DNS_CACHE_TIMEOUT 设置在内存中保存DNS信息的时间,默认为120秒。
1 2 3 4 5 6
| $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT,60); //只需要设置一个秒的数量就可以 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']); |