Categories: Development

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.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago