【问题标题】:PHP file_exists directoryPHP file_exists 目录
【发布时间】:2016-01-23 12:04:21
【问题描述】:

我正在尝试使用存在于子目录中的文件,但遇到了目录结构或其他问题。当从主目录调用时,此代码在较早时工作

包含该命令的文件位于域主目录下一个目录的子目录中。

当我在我知道存在的文件上调用以下内容时,不会返回任何内容,既不是 FALSE 也不是 TRUE

$imgpath1 = 'pics/'.$userid.'_pic.jpg';
$exists = file_exists($imgpath1);
echo "1".$exists;//returns 1

我尝试了目录的不同变体,例如“/pics...”和“../pics...”以及以“http://www....”开头的整个 url,但不能让它返回 FALSE 或 TRUE。

希望有任何建议。

【问题讨论】:

  • 尝试在 'pics/' 之前添加 realpath($_SERVER["DOCUMENT_ROOT"])
  • 你无法回应你的想法。而是使用var_dump($exists);
  • echo false 什么也没有打印出来。 echo true 会打印出 1,所以你必须得到布尔值 false,这意味着该目录不存在。您需要确切知道它相对于该脚本的工作目录的位置,或者提供它的绝对路径。
  • 好的。 vardump 打印出 false 以便问题得到解决。但是,该目录仍未被正确识别,因为该目录中确实存在文件。

标签: php directory file-exists


【解决方案1】:

true 强制转换为字符串时,您会得到1

false 强制转换为字符串时,会得到一个空字符串。

这是一个例子:

<?php
echo "True: \"" . true . "\"\n";
echo "False: \"" . false . "\"\n";

echo "True length: " . strlen("" . true) . "\n";
echo "False length: " . strlen("" . false) . "\n"
?>

以及运行它的输出:

True: "1"
False: ""
True length: 1
False length: 0

所以实际上,file_exists($imgpath1) 正在返回 false

【讨论】:

    【解决方案2】:

    您不能将Boolean 回显为TrueFalse,它将分别回显为10
    虽然,您可以使用ternary conditional operator,例如:

    $exists = file_exists($imgpath1);
    echo $exists ? 'true' : 'false';
    

    【讨论】:

      【解决方案3】:

      试试这个:

      var_dump(realpath(__DIR__.'/../pics'));
      

      如果你得到 false 路径不存在,否则你得到路径作为字符串。

      【讨论】:

        【解决方案4】:

        您可以使用以下代码。有点啰嗦。

        //get the absolute path /var/www/... 
        $currentWorkingDirectory = getcwd(); 
        
        //get the path to the image file
        $imgpath1 = $currentWorkingDirectory . '/pics/' . $userid . '_pic.jpg';
        
        //in case the pics folder is one level higher
        //$imgpath1 = $currentWorkingDirectory . '/../pics/' . $userid . '_pic.jpg';
        
        //test existence 
        if (file_exists($imgpath1)) {
            echo "The file $imgpath1 exists";
        } else {
            echo "The file $imgpath1 does not exist";
        }
        

        【讨论】:

          猜你喜欢
          • 2014-12-18
          • 2016-04-29
          • 2011-10-04
          • 2015-02-01
          • 2013-08-29
          • 2013-08-21
          • 2010-10-22
          • 2012-09-02
          • 2017-05-14
          相关资源
          最近更新 更多