【问题标题】:php check if file_exists() with htaccess mod_rewritephp 检查 file_exists() 是否与 htaccess mod_rewrite
【发布时间】:2016-02-17 13:21:09
【问题描述】:

我正在使用 htacces mod_rewrite 重写我的网站 URL,例如:

/dir/file.php
/dir/file_example.php
/dir/file2.php?id=test

成为

/dir/file
/dir/file-example
/dir/file2-test

一切正常。现在我有一个 PHP 脚本来执行某些重定向,但在重定向之前我想检查文件(或 url)是否存在:

if(file_exists("/dir/file2-test")){ // redirect on page
}else{ // redirect on index

但 file_exists() 在这种情况下返回 false。

还有另一种方法可以通过 php 检查这些页面/url(file2-test、file-example 等)是否存在?

PS:由于我的 htaccess 规则的复杂性,我无法在末尾附加“.php”。

【问题讨论】:

    标签: php apache .htaccess redirect mod-rewrite


    【解决方案1】:

    可以通过实际调用它来检查该 URL 是否确实存在,但代价是执行一个真正的 http 请求,并且由此引起的所有服务器负载和延迟。

    $file = 'http://www.domain.com/dir/file2-test';
    $file_headers = @get_headers($file);
    if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
        $exists = false;
    }
    else {
        $exists = true;
    }
    

    来源:http://www.php.net/manual/en/function.file-exists.php#75064

    我完全不推荐这个。

    我没有看到任何真正的机会从 php 中探查 RewriteEngine 逻辑,所以我建议将你的整个重写逻辑集成到 htaccess 或 php 中。

    【讨论】:

      【解决方案2】:

      首先,你必须检查绝对路径,然后你必须添加文件扩展名(对于文件):

      file_exists( $_SERVER['DOCUMENT_ROOT'].'/dir/file2-test.php') // check php file
      file_exists( $_SERVER['DOCUMENT_ROOT'].'/dir/file2-test')     // check directory
      

      或者,也许更好:

      file_exists( $_SERVER['DOCUMENT_ROOT'].$_SERVER['REQUEST_URI"].".php") // check php file
      file_exists( $_SERVER['DOCUMENT_ROOT'].$_SERVER['REQUEST_URI"])        // check directory
      

      但是——也可以使用段和/或查询——你应该使用parse_url

      $uri = parse_url( $_SERVER['REQUEST_URI'] );
      file_exists( $_SERVER['DOCUMENT_ROOT'].$uri['path'].".php") // check php file
      file_exists( $_SERVER['DOCUMENT_ROOT'].$uri['path'])        // check directory
      

      编辑:

      由于我的 htaccess 规则的复杂性,我无法在末尾附加“.php”。

      试试glob()

      $uri = parse_url( $_SERVER['REQUEST_URI'] );
      $files = glob( $_SERVER['DOCUMENT_ROOT'].$uri['path'].'*' );
      

      现在在$files 中,您将拥有以$_SERVER['DOCUMENT_ROOT'].$uri['path'] 开头的all 文件


      【讨论】:

      • 谢谢,但我需要检查 mod_rewrited URL 是否存在。我无法添加 .php
      • @ipel 另请注意,如果您的“复杂性”存在于查询中 (?...),parse_url 将解决它
      猜你喜欢
      • 2012-09-17
      • 1970-01-01
      • 1970-01-01
      • 2013-10-26
      • 2014-11-08
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多