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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago