【问题标题】:PHP if file exists, always show that existsPHP如果文件存在,总是显示存在
【发布时间】:2013-12-14 09:33:45
【问题描述】:

我有数据库列 attach1 和 attach2。 我需要显示这些列中的文件(pdf),但前提是它们存在于目录 www.domain.com/uploads 中。 Attach1 包含真实文件,但 attach2 不包含。

我尝试过这样的事情:

<?php
$file = $row['attach'];
$exists = file_exists('uploads/'.$file.''); 
if ($exists) {
  echo $file;
}
if (!$exists) {
  echo 'No file1';
}      
?>

<?php
$file2 = $row['attach2'];
$exists = file_exists('uploads/'.$file2.''); 
if ($exists) {
  echo $file2;
}
if (!$exists) {
  echo 'No file2';
}      
?> 

但每次它回复我时,该文件都存在,即使 attach2 不包含任何内容。为什么?

【问题讨论】:

  • 不是你的问题,但你的代码示例中有许多毫无意义的东西。您不需要将 ampty 字符串连接到文件名的末尾。您不需要将file_exists 的结果保存在变量中。您可以使用else 来简化条件。
  • 您是否尝试echo $file2 并确保它不为空?如果是,您将检查file_exists('/uploads'),当然是TRUE
  • 试试这个'if(isset($file)'
  • 是的,我确定它是空的。好的,如果我正在检查目录,如何检查具体文件?

标签: file echo exists


【解决方案1】:

如果您的文件名是空的,那么您只将目录名传递给file_exists。目录也是文件。而且我认为该目录确实存在。这不是在骗你。

您可以检查数据库中的文件名是否不为空,也可以将整个字符串传递给函数is_dir 以查看它是否为目录。我假设您只需要常规文件。

看起来像这样:

 <?php
 $file = $row['attach'];
 $exists = file_exists('uploads/'.$file.'') && !is_dir('uploads/'.$file.''); 
 if ($exists) {
   echo $file;
 } else {
   echo 'No file1';
 }      
 ?>

我将if 语句更改为使用else 子句。这相当于像您一样使用第二个if

【讨论】:

  • 我该怎么做?请。
  • 哪一部分? is_dir?
  • 效果很好。非常感谢。
  • @user2957822 很高兴我能提供帮助。
猜你喜欢
  • 2013-02-11
  • 2010-12-20
  • 2010-09-26
  • 1970-01-01
  • 2018-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
相关资源
最近更新 更多