【问题标题】:PHP file_exists() can't check file existence when URL rewrite is enabled?启用 URL 重写时 PHP file_exists() 无法检查文件是否存在?
【发布时间】:2023-03-29 02:11:01
【问题描述】:

在 Zend FW 中:

file_exists('xx/xxx/xxxx.jpg');

返回 1,但 xx/xxx/xxxx.jpg 不是文件或目录。

这是 Zend FW 返回的错误页面。因为它不是文件或有效的 url

如何检查文件是否存在?

【问题讨论】:

  • 该函数是原生 PHP 函数...尝试在没有 Zend 框架的 PHP 脚本中运行它,看看会发生什么。此外,开头的 / 表示它是从操作系统文件系统的顶部加载的,而不是从服务器 URL 的顶部加载的。
  • 还要注意 file_exists() 是缓存的,所以如果文件确实存在,则测试,然后删除,然后再次测试,第二次测试仍将返回 true。
  • 可以使用 clearstatcache() 清除缓存:php.net/manual/en/function.clearstatcache.php
  • file_exists() 没有检查 URL,因此您的错误页面与此无关。 (请注意,它可以在 一些 情况下检查 URL,但同样,这不是您在此处所做的。)
  • @thomas-hunter 我编辑我的问题并删除 /

标签: php zend-framework url-rewriting


【解决方案1】:

file_exists 检查文件或目录是否存在。 尝试使用is_file

【讨论】:

  • is_file 有效,为什么?我的文件系统中没有这样的文件或目录,但是 file_exists 返回 1 和 is_file 返回 0
  • 奇怪,也许你之前有一个文件或目录,它已经被 file_exists 缓存了
【解决方案2】:

要通过 HTTP 检查是否存在,您需要检查 HTTP 响应代码。 IMO 最简单的方法是使用 curl。试试这个:

$url = 'http://google.com/this_does_not_exist.jpg';
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);//timeout
$res = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

switch ($code % 100){
    case 2:  echo "exists\n"; break;
    case 3:  echo "too many redirects\n"; break;
    case 4:  echo "does not exist\n"; break;
    case 5:  echo "5xx error - may or may not exist once server fixed\n"; break;
    default:
             echo "Something weird. HTTP response code = $code\n";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 2023-01-02
    • 2012-04-18
    相关资源
    最近更新 更多