Are sockets available as an alternative for testing the existence of a remote file in PHP?

When testing the existence of a remote file in PHP, sockets can be used as an alternative method. By establishing a connection to the remote server using sockets, we can check if the file exists by sending a HEAD request and checking the response code. This can be useful when other methods like using file_exists() or fopen() are not suitable for remote files.

<?php
function remoteFileExists($url) {
    $urlParts = parse_url($url);
    $host = $urlParts['host'];
    $path = $urlParts['path'];
    
    $fp = fsockopen($host, 80, $errno, $errstr, 5);
    if (!$fp) {
        return false;
    } else {
        $out = "HEAD $path HTTP/1.1\r\n";
        $out .= "Host: $host\r\n";
        $out .= "Connection: Close\r\n\r\n";
        fwrite($fp, $out);
        
        $response = fgets($fp);
        fclose($fp);
        
        return strpos($response, '200 OK') !== false;
    }
}

// Example usage
$url = 'http://example.com/remote-file.txt';
if (remoteFileExists($url)) {
    echo 'Remote file exists!';
} else {
    echo 'Remote file does not exist.';
}
?>