ini_set('user_agent','Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0')
不過最近發現到如果呼叫的url過大,就有一定的機率回500錯誤  Orz...
解決方法:
GET:
  $opts = array(  
     'http'=>array(  
          'method'=>"GET",  
          'timeout'=>600,  
       )  
   );  
  $context = stream_context_create($opts);  
  file_get_contents($target_url, false, $context);
POST:
function Post($url, $post = null)  
{  
    $context = array();  
    if (is_array($post)) {  
        ksort($post);  
        $context['http'] = array (  
            'timeout'=>600,  
            'method' => 'POST',  
            'content' => http_build_query($post, '', '&'),  
         );  
    }  
    return file_get_contents($target_url, false, stream_context_create($context));  
}  
$data = array (  
    'name' => 'test',  
    'email' => 'test@gmail.com',  
    'submit' => 'submit',  
 );  
Post('http://www.example.com', $data);  
加上TimeOut時間就能避免了,不過就是等久了些使用者會不耐煩。在JQuery的非同步執行下~等久了有若干機會造成DB的Deadlock狀態(透過呼叫API同步資料再搭配系統操作...)。
PS. 建議使用curl或fsockopen來處理,file_get_contents用起來簡單但是其缺點也是挺無奈地,萬一主機商不給改php.ini 或是資料量大或運算/執行較久的頁面,那Debug起來不方便。
 
沒有留言:
張貼留言