2010-02-18 150 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. 
相关问题