代码之家  ›  专栏  ›  技术社区  ›  John

php:检查文件是否存在,但@get_headers会影响跟踪器

  •  2
  • John  · 技术社区  · 7 年前

    我正在使用PHP检查服务器上是否存在.html文件。但是,@get_headers在检查文件时似乎在“访问”页面,而生成分析报告的跟踪脚本正在将其作为页面视图进行处理。是否有其他方法可以检查文件是否存在而不发生这种情况?下面是我现在使用的代码:

    $file = "https://www." . $_SERVER['HTTP_HOST'] . $row['page'];
    $file_headers = @get_headers($file);
    if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
        $file_exists = false;
    }
    else {
        $file_exists = true;
    }
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   gone    7 年前

    @get-headers在检查文件时似乎在“访问”页面

    这正是它所做的,是的。

    是否有其他方法可以检查文件是否存在而不发生这种情况?

    通过检查文件是否存在。现在,您要检查的是“URL在被请求时是否返回错误”。

    如果您没有任何特殊的URL重写,您可以使用以下方法执行此操作:

    if (file_exists($_SERVER["DOCUMENT_ROOT"] . $row['page'])) {
        ....
    }
    
        2
  •  1
  •   Kep    7 年前

    如果你真的需要 get_headers 你可能会发现 Example #2 in the docs 乐于助人。

    简而言之: get_header 默认使用 GET 请求(无论如何- 页面视图)。

    示例2供参考:

    <?php
    // By default get_headers uses a GET request to fetch the headers. If you
    // want to send a HEAD request instead, you can do so using a stream context:
    stream_context_set_default(
        array(
            'http' => array(
                'method' => 'HEAD'
            )
        )
    );
    $headers = get_headers('http://example.com');
    ?>
    

    虽然我不喜欢更改默认的流上下文,但是我建议您创建自己的:

    <?php
    $context = stream_context_create(
        array(
            'http' => array(
                'method' => 'HEAD'
            )
        )
    );
    
    $headers = get_headers('http://example.com', 0, $context);
    ?>
    

    这是否有效主要取决于你的分析软件(即它区分了GET和HEAD请求)。

    推荐文章