2009-08-17 73 views
29

由於某些原因,下面的這段PHP代碼不起作用,我無法弄清楚。PHP的file_exists()不適合我嗎?

很奇怪, file_exists似乎是沒有看到的圖像是存在的,我檢查,以確保良好的文件路徑被插入file_exists功能,它仍然是演戲

如果我改變file_exists來!file_exists它將返回存在不存在

define('SITE_PATH2', 'http://localhost/'); 

$noimg = SITE_PATH2. 'images/userphoto/noimagesmall.jpg'; 
$thumb_name = 'http://localhost/images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg'; 
if (file_exists($thumb_name)) { 
    $img_name = $thumb_name; 
}else{ 
    $img_name = $noimg; 
} 
echo $img_name; 
+0

http://www.dreamincode.net/forums/topic/11197-checking-if-file-exists-on-remote-server/ – 2012-02-06 17:02:10

回答

68

file_exists()需要使用硬盤驅動器,而不是一個URL上的文件路徑中的圖像和那些。所以,你應該有更多的東西一樣:

$thumb_name = $_SERVER['DOCUMENT_ROOT'] . 'images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg'; 
if(file_exists($thumb_name)) { 
    some_code 
} 

http://us2.php.net/file_exists

+0

$ _ SERVER [ 'CONTEXT_DOCUMENT_ROOT']會工作如果你的別名不在你的文檔根目錄下,在這種情況下$ _SERVER ['DOCUMENT_ROOT']將失敗 – 2013-10-28 07:48:15

4

file_exists並僅在本地文件系統上工作。

如果你使用本地主機所以試試這個:

$thumb_name = 'images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg'; 
if (file_exists($_SERVER['DOCUMENT_ROOT'].$thumb_name)) { 
    $img_name = SITE_PATH2.$thumb_name; 
} else { 
    $img_name = $noimg; 
} 
10

docs說:

自PHP 5.0.0,這個功能也可以用一些 URL中使用包裝。請參閱List of Supported Protocols/Wrappers瞭解哪些包裝程序支持stat()功能系列。

+2

我不認爲每個文檔都支持stat()支持的協議列表中的HTTP/HTTPS - 只是一些「更傻」像php://內存等東西。 – AvatarKava 2009-08-17 13:08:41

+1

呵呵? http://docs.php.net/manual/en/wrappers.http.php – SilentGhost 2009-08-17 13:47:33

1

您是否啓用了允許您使用外部URL的選項?您可以在php.ini中設置:

allow_url_fopen = 1 
0

您必須編寫像"file:///C:/Documents%20and%20Settings/xyz/Desktop/clip_image001.jpg"這樣的文件路徑。

0

嘗試下面的一個。它的工作對我來說

define('SITE_PATH2', 'http://localhost/'); 
$noimg = SITE_PATH2. 'images/userphoto/noimagesmall.jpg'; 
$thumb_name = 'http://localhost/images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg'; 

if ($fileopen = @fopen($thumb_name)) { 
    $img_name = $thumb_name; 
    fclose($fileopen); 
}else{ 
    $img_name = $noimg; 
} 
echo $img_name;