How can I check if a URL exists via PHP?

How can I check if a URL exists via PHP?

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

Stefan Bogdanescu

Founder & Senior Architect

How can I check if a URL exists via PHP?

Determining whether a remote resource is accessible is a common requirement in web development, often needed before attempting to parse content or redirect users. In PHP, the most straightforward approach involves leveraging the native file_get_contents() function combined with error handling. However, relying solely on this method introduces significant ambiguity regarding what constitutes a "valid" URL versus one that exists but returns an empty response.

The core mechanism relies on triggering a warning when file_get_contents() fails to retrieve data. You can capture this state by enabling error reporting via error_reporting(E_ALL) or checking the return value directly. If the function returns false, it indicates that the request failed, potentially due to a 404 Not Found status, a network timeout, or a connection refusal. To distinguish between these scenarios without external libraries, you must inspect the $http_response_header variable, which is automatically populated during an HTTP request in PHP 5.2 and later.

$url = 'https://example.com/nonexistent-page';
$context = stream_context_create([
    'http' => [
        'ignore_errors' => true 
    ]
]);

$result = @file_get_contents($url, false, $context);

if ($result === false) {
    $headers = get_headers($url);
    
    if (!empty($headers)) {
        foreach ($headers as $header) {
            if (preg_match('/HTTP\/[\.0-9]+ ([0-9]+)/', $header, $matches)) {
                $status_code = $matches[1];
                if ((int)$status_code === 404) {
                    echo "URL exists but returned 404.";
                } else {
                    echo "Connection failed or other error occurred.";
                }
            }
        }
    } else {
        echo "Network connection failed.";
    }
}

This pattern demonstrates the trade-off between simplicity and precision. The @ operator suppresses the warning generated by file_get_contents(), allowing you to inspect the headers without cluttering your output immediately. However, this approach has a critical limitation: it does not handle HTTP redirects automatically. If the target URL returns a 301 or 302 status code, file_get_contents() will follow the redirect by default, which might mask an intermediate error or inflate the perceived size of the response if the final resource is large but you only needed to verify existence.

For more robust scenarios, especially when dealing with strict timeout requirements or custom headers, the stream_context_create function offers granular control over the request lifecycle. You can explicitly set follow_location to false to prevent automatic redirections, ensuring that a 302 status is treated as an error rather than a success. Additionally, setting a low timeout value prevents your script from hanging indefinitely if the remote server is unresponsive.

While native functions work for basic checks, they lack the convenience of modern HTTP client libraries. If you are already working within the Laravel ecosystem, utilizing the framework's built-in HTTP client provides a cleaner abstraction. The Illuminate\Http\Client facade allows you to check status codes without managing streams or headers manually. A simple call like Http::get($url)->status() returns the integer status code directly, making it trivial to differentiate between a 200 OK and a 404 Not Found.

use Illuminate\Http\Client;

$response = Client::get('https://example.com/check');
if ($response->successful() && !$response->isRedirect()) {
    // Content exists and is accessible
} elseif ($response->status() === 404) {
    // Resource exists but returns 404
} else {
    // Network error or redirect handling needed
}

This approach eliminates the need to parse header strings manually and handles SSL verification out of the box. It also integrates seamlessly with Laravel's configuration options for timeouts and proxies. If you are maintaining a legacy PHP application without Composer, sticking to the file_get_contents method with careful header inspection remains a viable strategy, provided you account for redirects and error suppression carefully.

Ultimately, the choice between native streams and modern HTTP clients depends on your project's constraints. Native functions offer zero dependencies, but they require more boilerplate to handle edge cases like redirects and status code parsing accurately. When reliability is paramount, leveraging established libraries ensures that your existence checks behave predictably across different server environments.

Our network