Skip to main content

Use PHP and cURL extension to check if a remote file exists.

<?php

function remoteFileExists()
{
    static $attempt = 0;
    
    $curl = curl_init('http://example/filename.txt');
    
    // don't fetch the actual page, you only want to check the connection is ok
    curl_setopt($curl, CURLOPT_NOBODY, true);
    
    // do request
    $result = curl_exec($curl);
    
    // if request did not fail
    if ($result !== false)
    {
        
        $attempt ++;
        
        // if request was ok, check response code
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        
        if ($statusCode == 404)
        {
            echo "File NOT found on attempt ({$attempt}). Will try again in 3-seconds...\n";
            sleep(3);
            
            remoteFileExists();
        }
        
        else
        {
            echo "File found on attempt ({$attempt}).\n";
            echo "Closing connection.";
        }
    }
    
    curl_close($curl);
}

echo remoteFileExists();
?>