WP-Mix

A fresh mix of code snippets and tutorials

PHP: Two Ways to Check if Remote File Exists

Working on my free WordPress plugin, Simple Download Counter, I needed a quick way to check if a remote file exists. As in, requesting the file returns a 200 “OK” response. Here are a couple of ways to do it via PHP.

Check via get_headers()

First way to check if an external/remote file exists is to use PHP’s get_headers() function. The following example checks if $file_path exists. If true, the variable returns the file URL. Otherwise the variable returns false.

$headers   = get_headers($file_path, true);
$response  = ($headers && isset($headers[0])) ? $headers[0] : null;
$file_path = (strpos($response, '200') === false) ? false : $file_path;

Notes: The $file_path variable should contain the URL that you want to check. Also, setting get_headers() second argument to true returns the response as an associative array. Otherwise it would just be a numerically indexed array. Lastly, remember to apply proper sanitization as needed when working with unknown variables.

Check via fopen()

The next way to check if a remote (external) file exists, is to use PHP’s fopen() function. The following example checks if $file_path exists. If true, the variable returns the file URL. Otherwise the variable returns false.

$handle = fopen($file_path, 'r');
$file_path = (!$handle) ? false : $file_path;

For more context, check out simple_download_counter_parse_file_path(), located in the free WordPress plugin, Simple Download Counter.

★ Pro Tip:

USP ProSAC Pro