How to check if a file exists from a URL with PHP

How to check if a file exists on a remote server or network from a URL with PHP.

Using file_exists() only works for directory links (files on the system) and using cURL is somewhat too much when all you need to do is get the HTTP code of the URL request.

get_headers() will return an array with the headers from an HTTP request.

An example get_headers() response:

[
   "HTTP/1.1 200 OK",
   "Date: Mon, 07 Jun 2021 13:30:57 GMT",
   "Server: Apache/2.4.41 (Ubuntu)",
   "Last-Modified: Thu, 29 Apr 2021 06:27:59 GMT",
   "ETag: 0-5c11698b76a05",
   "Accept-Ranges: bytes",
   "Content-Length: 4565",
   "Connection: close",
   "Content-Type: application/json"
]

The first index has the HTTP response code, HTTP code 200 means the request was a success (file exists). You will get a 404 code if nothing exists for the request.

A function can be built using str_contains() on the first array index to check for “200 OK”

function URL_exists(string $url): bool
{
    return str_contains(get_headers($url)[0], "200 OK");
}

If the “200 OK” is found then true is returned else false is returned.

Here is the function in use:

if (URL_exists("https://domain.com/directory/a_file.json")){
    echo "Exists";
} else {
    echo "Nothing here";
}

This can now be used to check if a file exists from a URL.