PHP文件是否存在

5

这是我的代码。

$filename = "$myMedia catalog/category/ $myImage.png";
$filename = str_replace(" ", "", $filename);

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

上面的变量输出了http://50.87.6.244/~storeupp/media/catalog/category/Game_Used.png,它是存在的。然而,它显示不存在。
你有什么想法吗?

抱歉,我进行了搜索但是找不到问题所在 :( - user1717480
2
如果你接下来要删除空格,为什么要在$filename中放置空格呢? - Barmar
可能是重复的问题:PHP:如何检查图像文件是否存在? - Cees Timmerman
6个回答

5

只需像这样使用:

 $filename = dirname(__FILE__) . "/ $myMedia catalog/category/ $myImage.png";
 $filename = str_replace(" ", "", $filename);

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

非常感谢!是的,我只需要删除http://并仅包含目录网址。谢谢!7分钟后将接受:) +投票 - user1717480

4

我不确定,但我认为如果您将外部网络项作为资产,则以下代码将更加成功:

$filename = $myMedia."catalog/category/".$myImage.".png";
$headers = @get_headers($filename);
$exists = ($file_headers[0] == 'HTTP/1.1 404 Not Found');

2

OT:不要使用空格和str_replace(" ", "", $filename)来处理文件名,你可以在变量周围使用“{}”括号。

$filename = "{$myMedia}catalog/category/{$myImage}.png";


这样做可以更加简洁明了地处理文件名。

0

那个文件看起来好像在你的网站根目录之外,结果它无法通过网络访问。如果你想查看本地机器上的文件,请使用文件根目录。(例如:/path/to/media/catalog/category/Game_Used.png)


0

您需要引用文件或目录的路径,不能使用http://链接。

file_exists文档


0
文档中指出,file_exists()函数仅在PHP 5.0及以上版本的某些URL包装器中可用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接