首页 > 解决方案 > PHP:file_exists 总是返回 FALSE

问题描述

背景:

我正在尝试向我的用户提供 PDF 文件,但对其他人不可用。建议似乎是将这些放在站点根目录之上但网络根目录之下。第一步是测试文件是否存在,结果始终为 FALSE。问题:为什么 file_exists 总是返回 false?尝试的事情 1. 在 Web 根目录中创建名为“a”的目录(以避免拼写错误)。file_exists("/a/") 为假 file_exists("/a/info.pdf") 为假,尽管文件存在 2. clearstatcache(); 在 file_exists 3. 添加 allow_url_fopen = on 到根目录下的 php.ini 之前

enter code here

  clearstatcache();  
  $full_path = '/a/info.pdf';  // absolute physical path to file below web root.
  if ( file_exists($full_path) )
     {
     $mimetype = 'application/pdf';

     header('Cache-Control: no-cache');
     header('Cache-Control: no-store');
     header('Pragma: no-cache');
     header('Content-Type: ' . $mimetype);
     header('Content-Length: ' . filesize($full_path));

     $fh = fopen($full_path,"rb");
     while (!feof($fh)) { print(fread($fh, filesize($full_path))); }
     fclose($fh);
     }
   else die("File does not exist on the server - .");

总是遵循 else 。我还能尝试什么?

标签: phpfileexists

解决方案


当您像/a/file.pdf那样使用完整路径时,实际上您试图从整个服务器的根文件夹中获取文件,而不是您在服务器中的帐户的 DOCUMENT_ROOT。

例如:

您有帐户,公共文件夹是:

/home/{ACCOUNT_NAME}/public_html/index.php

因此,当您尝试“/a/file.pdf”时,您不会得到:

/home/{ACCOUNT_NAME}/a/file.pdf

您只需要在您的帐户中定义和检查绝对路径,

例如,正如我所写,对您的帐户使用完整路径:

/home/{ACCOUNT_NAME}/a/file.pdf

如果您尝试使用 index.php 文件,甚至可以使用相对路径:

../a/file.pdf

如果您不知道帐户的完整路径,

看看你有什么: $_SERVER['DOCUMENT_ROOT'] 变量


推荐阅读