2014-08-28 49 views
-2

我有一個簡單的代碼來檢查文件是否存在於服務器中。如何知道我的圖像是否存在於服務器上? (PHP)

<?php 
$filename = 'www.testserver/upload/productimg/IN.ZL.6L_sml.jpg'; 

if (file_exists($filename)) { 
     echo "The file $filename exists"; 
} else { 
     echo "The file $filename does not exist"; 
} 
?> 

問題:我的本地網絡服務器說,即使當我複製粘貼到瀏覽器的網址雖然,我可以看到圖像的文件不存在。

如何讓條件說文件不存在?

+0

您需要構建與web服務器「DOCUMENT_ROOT」相關的本地路徑,而不是使用類似URL的字符串。 – mario 2014-08-28 13:50:49

+2

'www.testserver/...'不是有效的**文件路徑**。無論你是在談論遠程服務器上的URL,在這種情況下,你需要使用'http:// www ...',或者你的意思是一個*本地*文件在同一臺服務器上,在這種情況下,你需要使用'/ usr/local/var/...'這樣的* local *文件路徑。 – deceze 2014-08-28 13:52:02

+0

是'www'actually你的路徑的一部分?它是一個文件夾嗎?如果不是,你可能不應該在'file_exists'函數中使用它,而是使用本地路徑代替... – 2014-08-28 13:52:26

回答

0

圖像的真實路徑,你可以嘗試:

<?php 
$filename = 'www.testserver/upload/productimg/IN.ZL.6L_sml.jpg'; 
$testImage = @file_get_contents($filename); 

if ($testImage != NULL) { 
    echo "The file $filename exists"; 
} else { 
    echo "The file $filename does not exist"; 
} 
?> 
1

另一種選擇是,提出請求並檢查響應頭:

<?php 
    $headers = get_headers('http://www.example.com/file.jpg'); 

    if($headers[0]=='HTTP/1.0 200 OK'){ 
     return true; // file exists 
    }else{ 
     return false; // file doesn't exists 
    } 
    ?> 

代碼活生生的例子:
http://codepad.viper-7.com/qfnvme

0

使用

$filename = $_SERVER["DOCUMENT_ROOT"]."/upload/productimg/IN.ZL.6L_sml.jpg"; 

用於測試文件。

相關問題