PHP 如果文件存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15074013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:30:34  来源:igfitidea点击:

PHP if file exists

php

提问by

Here is my code.

这是我的代码。

$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";
}

The variableabove outputs http://50.87.6.244/~storeupp/media/catalog/category/Game_Used.pngwhich does exist. However, it says that it does not exists.

variable上述输出http://50.87.6.244/~storeupp/media/catalog/category/Game_Used.png其确实存在。但是,它说它不存在。

Any idea why?

知道为什么吗?

采纳答案by Vineet1982

Just try to use like this:

试着像这样使用:

 $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";
 }

回答by Michael

I don't know, but I think, the following code will be more successful if you have external web items as assets:

我不知道,但我认为,如果您将外部网络项目作为资产,以下代码会更成功:

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

回答by user2410595

OT: Instead of using spaces and str_replace(" ", "", $filename) you can surround variable betwen "{}" brackets.

OT:您可以将变量括在“{}”括号之间,而不是使用空格和 str_replace(" ", "", $filename)。

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

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

回答by John Conde

That file looks like it is outside of your web root. As a result it is not available via the web. If you're trying to check a file that is local on your machine, use the file root instead. (i.e. /path/to/media/catalog/category/Game_Used.png)

该文件看起来像是在您的 Web 根目录之外。因此,它无法通过网络获得。如果您尝试检查计算机上的本地文件,请改用文件根目录。(即/path/to/media/catalog/category/Game_Used.png)

回答by Matt Busche

You need to reference the path to the file or the directory you cannot use http://links

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

file_exists documentation

file_exists 文档

回答by christopher

In the documentationit states that the file_exists() function is only available with some URL wrappers as of PHP 5.0.

文档中,它指出 file_exists() 函数仅适用于 PHP 5.0 的某些 URL 包装器。