file_get_contents函數我們通常是拿來對文件操作了,下面一起來看看file_get_contents函數的高級使用方法吧.
首先解決file_get_contents的超時問題,在超時返回錯誤后就象js中的settimeout那樣進行一次嘗試,錯誤超過3次或者5次后就確認為無法連線伺服器而徹底放棄.
這就簡單介紹兩種解決方法:
一、增加超時的時間限制
注意:set_time_limit只是設定你的PHP程式的超時時間,而不是file_get_contents函數讀取URL的超時時間.
我一開始以為set_time_limit也能影響到file_get_contents,后來經測試是無效的,真正的修改file_get_contents延時可以用resource $context的timeout參數.
PHP程式碼:
- $opts = array(
- 'http'=>array(
- 'method'=>"GET",
- 'timeout'=>60,
- )
- );
- $context = stream_context_create($opts);
- $html =file_get_contents('http://www.companysz.com', false, $context);
- fpassthru($fp);
二、多次嘗試,PHP程式碼:
- $cnt=0;
- while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE){
- $cnt++;
- }
以上方法對付超時已經OK了,接下來演示一下用file_get_contents實現Post,如下:
- function Post($url, $post = null){
- $context = array();
- if (is_array($post)) {
- ksort($post);
- $context['http'] = array (
- 'timeout'=>60,
- 'method' => 'POST',
- 'content' => http_build_query($post, '', '&'),
- );
- }
- return file_get_contents($url, false, stream_context_create($context));
- }
- $data = array (
- 'name' => 'test',
- 'email' => '[email protected]',
- 'submit' => 'submit',
- );
- echo Post('http://www.companysz.com', $data);
注意檔案頭的Set_time_out否則整個檔案都得超時了.
新聞熱點
疑難解答