欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

深入php函數(shù)file_get_contents超時處理的方法詳解

 更新時間:2013年06月03日 16:45:36   作者:  
本篇文章是對php函數(shù)file_get_contents超時處理的方法進行了詳細的分析介紹,需要的朋友參考下
一.增加超時的時間限制
這里需要注意:set_time_limit只是設(shè)置你的PHP程序的超時時間,而不是file_get_contents函數(shù)讀取URL的超時時間。真正的修改 file_get_contents延時可以用resource $context的timeout參數(shù):
復(fù)制代碼 代碼如下:

$opts = array( 
    'http'=>array( 
        'method'=>"GET", 
        'timeout'=>60, 
    )  ); 
$context = stream_context_create($opts);       $html =file_get_contents('http://www.example.com', false, $context);

二、一次有延時的話那就多試幾次
有時候失敗是因為網(wǎng)絡(luò)等因素造成,沒有解決辦法,但是可以修改程序,失敗時重試幾次,仍然失敗就放棄,因為file_get_contents()如果失敗將返回 FALSE,所以可以下面這樣編寫代碼:
$cnt=0;
while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE) $cnt++;
以上方法對付超時已經(jīng)OK了。
有人發(fā)現(xiàn)了'method'=>”GET”,GET也可以設(shè)置成post,函數(shù)如下
復(fù)制代碼 代碼如下:

   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' => 'test@gmail.com',
       'submit' => 'submit',
   );

   echo Post('http://www.example.com', $data);

相關(guān)文章

最新評論