标签:
HTTP请求有两个超时时间:一个是连接超时时间,另一个是数据传输的最大允许时间(请求资源超时时间)。
<?php // create a new cURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); curl_setopt($ch, CURLOPT_TIMEOUT, 30); // grab URL and pass it to the browser curl_exec($ch); // close cURL resource, and free up system resources curl_close($ch); var_dump(curl_error($ch));
<?php $fp = fsockopen("www.example.com", 80); if (!$fp) { echo "Unable to open\n"; } else { fwrite($fp, "GET / HTTP/1.0\r\n\r\n"); stream_set_timeout($fp, 2); $res = fread($fp, 2000); $info = stream_get_meta_data($fp); fclose($fp); if ($info[‘timed_out‘]) { echo ‘Connection timed out!‘; } else { echo $res; } } ?>
连接超时时间和数据传输的最大允许时间均为设置的timeout,如
<?php $timeout = 60; $options = array( ‘http‘=>array( ‘method‘=>"GET", ‘header‘=>"Accept-language: en\r\n", ‘timeout‘ => $timeout ) ); $context = stream_context_create($options); $contents = file_get_contents($source, false, $context); ?>
function http_request($url, $post = null) { $timeout=30; if(is_array($post)) { ksort($post); $options[‘http‘] = array ( ‘timeout‘=>$timeout, ‘method‘ => ‘POST‘, ‘content‘ => http_build_query($post, ‘‘, ‘&‘), ); } $context = stream_context_create($options); return file_get_contents($url, false, $context); }
标签:
原文地址:http://www.cnblogs.com/phpfans/p/4349043.html