file_exists() 适用于字符串,但不适用于字符串变量

问题描述 投票:0回答:2

我对 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';
  }
php file-exists
2个回答
0
投票

这里为遇到此问题的人提供一些帮助:仔细检查您的变量以确保其正确。

您是否对输入进行了清理,以便您要查找的字符真正匹配?

如果您使用的是 ffmpeg 之类的东西,例如您需要将路径放在双引号中,即文件名可以是“myVideo.mp4”而不是 myVideo.mp4,这意味着如果您将其作为变量传递,您将传递“myVideo.mp4”而不是“myVideo.mp4”

你的正斜杠/反斜杠正确吗?

您的起始目录是您认为的那样吗?

如果没有,用 Chdir() 更改它;


-1
投票

is_file建议使用来验证文件,可能会给您的路线带来不便,请更改

$file = $_SERVER['DOCUMENT_ROOT'].'/mysite/test_file.txt';

is_filefile_exists 是两个原生 PHP 函数,可用于验证特定文件是否存在。虽然他们的名字相当具有描述性,但你应该知道:

    仅当最后一个函数的路径实际上是现有文件时,
  1. is_file才返回 true。
  2. file_exists 过去是否是文件路径作为有效目录返回 true(如果要专门检查路径是否是目录而不是文件,请使用 is_dir)。

这个区别非常重要。如果您的目标不仅仅是文件和目录,那么 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
© www.soinside.com 2019 - 2024. All rights reserved.