模拟HTTP请求超时时间设置
HTTP请求有两个超时时间:一个是连接超时时间,另一个是数据传输的最大允许时间(请求资源超时时间)。
使用curl命令行
使用PHP的curl_init
<?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的fsockopen
<?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; } } ?>
使用file_get_contents
连接超时时间和数据传输的最大允许时间均为设置的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); ?>
file_get_contents模拟post和get
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); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。