我对 PHP 中的函数 file_exists() 有问题。下面代码的结果始终是“存在于字符串”,但在我看来它应该打印两条消息。
$file = 'test_file.txt';
if (file_exists($file)){
echo 'Exists on variable';
}
if (file_exists('test_file.txt'){
echo 'Exists on string';
}
这里为遇到此问题的人提供一些帮助:仔细检查您的变量以确保其正确。
您是否对输入进行了清理,以便您要查找的字符真正匹配?
如果您使用的是 ffmpeg 之类的东西,例如您需要将路径放在双引号中,即文件名可以是“myVideo.mp4”而不是 myVideo.mp4,这意味着如果您将其作为变量传递,您将传递“myVideo.mp4”而不是“myVideo.mp4”
你的正斜杠/反斜杠正确吗?
您的起始目录是您认为的那样吗?
如果没有,用 Chdir() 更改它;
is_file建议使用来验证文件,可能会给您的路线带来不便,请更改
$file = $_SERVER['DOCUMENT_ROOT'].'/mysite/test_file.txt';
is_file 和 file_exists 是两个原生 PHP 函数,可用于验证特定文件是否存在。虽然他们的名字相当具有描述性,但你应该知道:
这个区别非常重要。如果您的目标不仅仅是文件和目录,那么 is_file 就是您的函数。如果您想随意检查目录或文件,请选择 file_exists
示例:
$file ='mysite/public_html/folder/file.php';
$directory ='/mysite/public_html/folder/';
$exists = is_file( $file );//return true
$exists = is_file( $directory ); //return false
$exists = file_exists( $file );//return true
$exists = file_exists( $directory ); //return true