Search code examples
phpfile-header

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


I'm using PHP to check if an .html file exists on the server. However, @get_headers seems to be "visiting" the page when it checks for the file, and my tracking script that produces an analytics report is picking that up as a page view. Is there another way to check if the file exists without that happening? Here's the code I'm using now:

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

Solution

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

    That's exactly what it's doing, yes.

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

    By checking whether the file exists. Right now, what you're checking is "whether the URL returns an error when requested".

    If you don't have any special URL rewrites in place, you could probably do this with:

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