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

PHP: Checking if file exists, but @get_headers affecting tracker

我正在使用 PHP 检查服务器上是否存在 .html 文件。但是,@get_headers 在检查文件时似乎是 "visiting" 页面,而我生成分析报告的跟踪脚本正在将其作为页面视图。有没有另一种方法来检查文件是否存在而不发生这种情况?这是我现在使用的代码:

$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;
}

如果您确实需要使用 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 请求)。

@get_headers seems to be "visiting" the page when it checks for the file

这正是它正在做的,是的。

Is there another way to check if the file exists without that happening?

通过检查文件是否存在。现在,您正在检查的是 "whether the URL returns an error when requested".

如果您没有任何特殊的 URL 重写,您可以这样做:

if (file_exists($_SERVER["DOCUMENT_ROOT"] . $row['page'])) {
    ....
}