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

时间:2019-02-10 22:36:06

标签: php file-header

我正在使用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 个答案:

答案 0 :(得分:4)

  

@get_headers在检查文件时似乎正在“访问”页面

这就是它的作用,是的。

  

是否还有另一种方法来检查文件是否存在而没有发生?

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

如果您没有任何特殊的URL重写,则可以执行以下操作:

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

答案 1 :(得分:1)

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