2010-02-18 158 views
6

如何檢查外部服務器上是否存在文件?我有一個網址「http://logs.com/logs/log.csv」,我在另一臺服務器上有一個腳本來檢查這個文件是否存在。我試圖如何檢查外部服務器上是否存在文件

$handle = fopen("http://logs.com/logs/log.csv","r"); 
if($handle === true){ 
return true; 
}else{ 
return false; 
} 

if(file_exists("http://logs.com/logs/log.csv")){ 
return true; 
}else{ 
return false; 
} 

這些methos只是不工作

+1

嘗試'如果($處理)'。 '$ handle'不會是一個布爾值,所以將它與一個比較沒有意義。 – Skilldrick

+0

類似的問題:http://stackoverflow.com/questions/2280394 – Gordon

回答

1
<?php 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, 4file dir); 
    curl_setopt($ch, CURLOPT_HEADER, true); 
    curl_setopt($ch, CURLOPT_NOBODY, true); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10); 

    $data = curl_exec($ch); 
    curl_close($ch); 

    preg_match_all("/HTTP\/1\.[1|0]\s(\d{3})/",$data,$matches); //check for HTTP headers 

    $code = end($matches[1]); 

    if(!$data) 
    { 
     echo "file could not be found"; 
    } 
    else 
    { 
     if($code == 200) 
     { 
      echo "file found"; 
     } 
     elseif($code == 404) 
     { 
      echo "file not found"; 
     } 
    } 
    ?> 
+0

有沒有一些方法可以直接抓取網址的數據,只需調用一次就可以調用它們? – My1

3

這應該工作:

$contents = file_get_contents("http://logs.com/logs/log.csv"); 

if (strlen($contents)) 
{ 
    return true; // yes it does exist 
} 
else 
{ 
    return false; // oops 
} 

注:這是假設文件不爲空

+1

如果文件存在但是空白怎麼辦? – Skilldrick

+0

@Skilldrick:你是對的,修改答案。 – Sarfraz

+0

如果文件非常大,這將會很有趣 – eithed

8
function checkExternalFile($url) 
{ 
    $ch = curl_init($url); 
    curl_setopt($ch, CURLOPT_NOBODY, true); 
    curl_exec($ch); 
    $retCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    curl_close($ch); 

    return $retCode; 
} 

$fileExists = checkExternalFile("http://example.com/your/url/here.jpg"); 

// $fileExists > 400 = not found 
// $fileExists = 200 = found. 
相關問題