首先解決file_get_contents的超時(shí)問(wèn)題,在超時(shí)返回錯(cuò)誤後就象js中的settimeout那樣進(jìn)行一次嘗試,錯(cuò)誤超過(guò)3次或者5次後就確認(rèn)為無(wú)法連線伺服器而徹底放棄。這裡就簡(jiǎn)單介紹兩種解決方法:一、增加超時(shí)的時(shí)間限制注意:set_time_limit只是設(shè)定你的php程式的超時(shí)時(shí)間,而不是file_get_contents函數(shù)讀取URL的超時(shí)時(shí)間。我一開(kāi)始以為set_time_limit也能影響到file_get_contents,後來(lái)經(jīng)測(cè)試是無(wú)效的。真正的修改file_get_contents延時(shí)可以用resource $context的timeout參數(shù):PHP程式碼 $opts = array( 'http'=>array( 'method'=>"GET", 'timeout'=>60, ) ); $context = stream_context_create($opts); $html =file_get_contents('http://www.example.com', false, $context); fpassthru($fp);二、多次嘗試PHP程式碼 $cnt=0; while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE){ $cnt++; }以上方法對(duì)付超時(shí)已經(jīng)OK了。接下來(lái)演示一下用file_get_contents實(shí)現(xiàn)Post,如下:PHP程式碼 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);注意檔案頭的Set_time_out否則整個(gè)檔案都得超時(shí)了
|
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注