【问题标题】:PHP's file_exists() will not work for me?PHP file_exists() 对我不起作用?
【发布时间】:2010-11-20 05:52:57
【问题描述】:

由于某种原因,下面的 PHP 代码无法运行,我无法弄清楚。

这很奇怪, file_exists 似乎没有看到该图像确实存在,我已检查以确保将一个好的文件路径插入到 file_exists 函数中并且它仍在起作用

如果我将 file_exists 更改为 !file_exists,它将返回一个存在和不存在的图像

define('SITE_PATH2', 'http://localhost/');

$noimg = SITE_PATH2. 'images/userphoto/noimagesmall.jpg';
$thumb_name = 'http://localhost/images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if (file_exists($thumb_name)) {
    $img_name = $thumb_name;
}else{
    $img_name = $noimg;
}
echo $img_name;

【问题讨论】:

标签: php file-exists


【解决方案1】:

file_exists() 需要使用硬盘驱动器上的文件路径,而不是 URL。所以你应该有更多类似的东西:

$thumb_name = $_SERVER['DOCUMENT_ROOT'] . 'images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if(file_exists($thumb_name)) {
    some_code
}

http://us2.php.net/file_exists

【讨论】:

  • 如果您的别名不在文档根目录下,$_SERVER['CONTEXT_DOCUMENT_ROOT'] 将起作用,在这种情况下 $_SERVER['DOCUMENT_ROOT'] 将失败
  • 我知道大多数人使用的文件路径/url。但是如果您仍然遇到问题,请不要忘记检查基本内容,例如,我在框架中使用别名作为路径,但忘记将别名解析为检查中的实际路径。
【解决方案2】:

docs说:

从 PHP 5.0.0 开始,此函数也可以与 一些 URL 包装器一起使用。请参阅 List of Supported Protocols/Wrappers 了解哪些包装器支持 stat() 系列功能。

【讨论】:

  • 我不相信 HTTP/HTTPS 在 stat() 支持的协议列表中每个文档 - 只是一些“愚蠢”的东西,比如 php://memory。
【解决方案3】:

file_exists 仅适用于本地文件系统。

所以如果你使用 localhost 试试这个:

$thumb_name = 'images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if (file_exists($_SERVER['DOCUMENT_ROOT'].$thumb_name)) {
    $img_name = SITE_PATH2.$thumb_name;
} else {
    $img_name = $noimg;
}

【讨论】:

    【解决方案4】:

    您是否启用了允许您使用外部 URL 的选项?可以在 php.ini 中设置:

    allow_url_fopen = 1
    

    【讨论】:

      【解决方案5】:

      http://php.net/manual/en/function.file-exists.php

      你检查过下面的cmets吗?

      只是阅读了部分内容,但似乎有几个问题。

      缓存可能是个问题。 打开 FTP url 时,它总是返回 true(他们在 cmets 中说) ...

      【讨论】:

        【解决方案6】:

        你必须写像"file:///C:/Documents%20and%20Settings/xyz/Desktop/clip_image001.jpg"这样的文件路径。

        【讨论】:

          【解决方案7】:

          试试下面的一个。它对我有用

          define('SITE_PATH2', 'http://localhost/');
          $noimg = SITE_PATH2. 'images/userphoto/noimagesmall.jpg';
          $thumb_name = 'http://localhost/images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
          
          if ($fileopen = @fopen($thumb_name)) {
              $img_name = $thumb_name;
              fclose($fileopen);
          }else{
              $img_name = $noimg;
          }
          echo $img_name;
          

          【讨论】:

            猜你喜欢
            • 2017-05-14
            • 2017-03-11
            • 2011-11-05
            • 1970-01-01
            • 2012-07-08
            • 1970-01-01
            • 2014-08-05
            • 2015-11-09
            • 2011-09-03
            相关资源
            最近更新 更多