2015-01-16 96 views
1

我正在使用file_get_contents在我的網站上運行一個php腳本,將導出一些文本文件中的數據。 php腳本「export.php」在作業完成時輸出「OK」,如果發生錯誤則輸出「Error」。PHP:空的結果 - file_get_contents

如果我在瀏覽器中運行export.php,它將打印「OK」,如果我通過在另一個php腳本中調用file_get_contents運行它,結果爲空。但在任何情況下,export.php都會打印「確定」或「錯誤」。

這是我的腳本調用export.php:

$opts = array('http' => 
       array(
        'method' => 'GET', 
        'timeout' => 240 
       ) 
      ); 

      $context = stream_context_create($opts); 
      $url_pre = "http://"; 
      $url = "127.0.0.1/export.php"; 
      $html = @file_get_contents($url_pre.$url,false,$context); 
      if ($html === false){ 
       $job_ok=false; 
       $result=error_get_last(); 
       echo "Error: ".$result."<br />"; 
      }else{ 
       if (substr($html,0,2)=="OK"){ 
        $job_ok=true; 
        $errurl = ""; 
        $result="Job done"; 
        echo "Job done: ".$result."<br />"; 
       }else{ 
        $job_ok=false; 
        $errurl = $url_pre.$url; 
        $result=$html; 
        echo "Error: ".$result."<br />"; 
       } 
      } 
      echo "HTML: $html <br />"; 

腳本的結果是:

Error:

如果我在瀏覽器中打開 「http://127.0.0.1/export.php」 我得到:

OK

也許有人可以幫助我!

謝謝!

+0

我沒有看到什麼不好。我從來沒有通過IP調用本地文件。試圖使用'本地主機'而不是IP? – Forien

+3

從'@ file_get_contents'中刪除'@'來查看函數是否返回錯誤 – violator667

+0

我從file_get_contents中刪除@並沒有得到任何錯誤。我也試過本地主機,但不會工作。也許腳本會出現任何超時。因爲在瀏覽器中加載頁面大約需要60秒。 – Mike

回答

1

我已經改變了file_get_contents捲曲,現在它的工作!

function curl_file_get_contents($url){ 
$curl = curl_init(); 
$userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)'; 

curl_setopt($curl,CURLOPT_URL,$url); //The URL to fetch. This can also be set when initializing a session with curl_init(). 
curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE); //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly. 
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5); //The number of seconds to wait while trying to connect. 

curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); //The contents of the "User-Agent: " header to be used in a HTTP request. 
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE); //To fail silently if the HTTP code returned is greater than or equal to 400. 
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); //To follow any "Location: " header that the server sends as part of the HTTP header. 
curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE); //To automatically set the Referer: field in requests where it follows a Location: redirect. 
curl_setopt($curl, CURLOPT_TIMEOUT, 240); //The maximum number of seconds to allow cURL functions to execute. 

$contents = curl_exec($curl); 
curl_close($curl); 
return $contents; 
}