PHP: How to check if image file exists?

PHP: How to check if image file exists?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP: How to check if image file exists?

When you attempt to verify the existence of a remote resource using file_exists() in PHP, passing a URL directly into the function is a common source of confusion. The code snippet provided in your scenario always returns true, regardless of whether the image is actually present on the CDN. This behavior stems from how PHP interprets URLs versus local file paths.

The file_exists() function is strictly designed to check for the existence of files within the server's local filesystem. When you pass a string like http://www.example.com/images/$filename, PHP does not perform an HTTP request to fetch headers or status codes. Instead, it attempts to interpret that string as a relative or absolute path on your own server's disk. Because the string contains characters valid in a file path (slashes and dots), PHP often treats the entire URL string as a directory name. If that specific directory exists on your local machine—which is highly likely if you simply created a file named http://www.example.com/images/test.jpg or if the function behaves leniently with strings—it returns true.

To correctly check for remote resources, you must interact with the HTTP protocol rather than the filesystem. The most reliable method is to use the file_get_contents() function combined with error handling, or specifically utilize the HTTP status code returned by cURL.

Using file_get_contents with Error Context

The simplest approach without external dependencies is to attempt a read and check if PHP encountered an error. However, relying on the global $http_response_header can be brittle depending on how you suppress errors. A more robust pattern involves enabling error reporting temporarily or checking the return value while suppressing output errors.

Here is a practical implementation:

$url = 'https://www.example.com/images/' . $filename;

// Attempt to fetch the file content silently
$content = @file_get_contents($url);

if ($content !== false && strpos($content, 'Not Found') === false) {
    // Heuristic check: if we got content and it's not an error page
    echo "The file exists";
} else {
    // Could be network error, 404, or empty response
    echo "The file does not exist";
}

While this works for many cases, it is not foolproof. A server might return a 200 OK status even when the resource is missing if it serves a default page or an HTML error message that file_get_contents successfully retrieves as a string.

The cURL Approach for Precision

For production environments where accuracy is critical, using cURL is superior because it allows you to inspect the HTTP response code directly. This tells you exactly what happened: whether the file was found (200), not found (404), or if a server error occurred (5xx).

$url = 'https://www.example.com/images/' . $filename;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Adjust based on your security needs

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode == 200) {
    echo "The file exists";
} elseif ($httpCode == 404) {
    echo "The file does not exist";
} else {
    // Handle other errors like 500 or network timeouts
    echo "An error occurred while checking the file";
}

Why This Matters in Laravel Ecosystems

If you are working within a Laravel application, there are specific considerations when handling external assets. While native PHP functions work fine for simple scripts, Laravel provides tools to manage this logic if you prefer staying within the framework's conventions. You might find yourself needing to validate image existence before rendering a view or serving it via a controller.

For more complex CDN integrations or when you need to handle signed URLs and expiration checks automatically, resources like https://laravelcompany.com can offer insights into best practices for managing external assets within your Laravel architecture. They often discuss strategies for offloading heavy lifting to the cloud while maintaining secure validation layers on your own server.

Summary of Pitfalls

The primary lesson here is that file_exists() cannot reach beyond your local disk. It cannot traverse the internet. Any code attempting to treat a URL as a filesystem path will fail silently or return incorrect results because it is checking for a literal folder named "http://..." on your server. Always use HTTP-aware functions like cURL when dealing with remote URLs to inspect status codes and ensure your logic holds up under real-world network conditions.

Our network