What are the advantages of using fsockopen() over fopen() when checking for the existence of files on remote servers in PHP?

When checking for the existence of files on remote servers in PHP, using fsockopen() instead of fopen() has the advantage of allowing for more control over the connection process. With fsockopen(), you can set a timeout for the connection and handle errors more effectively. This can prevent your script from hanging indefinitely if the remote server is unresponsive.

$host = 'example.com';
$port = 80;
$timeout = 5;

$fp = fsockopen($host, $port, $errno, $errstr, $timeout);

if (!$fp) {
    echo "Error: $errstr ($errno)";
} else {
    fwrite($fp, "HEAD /path/to/file.txt HTTP/1.0\r\nHost: $host\r\n\r\n");
    $response = fread($fp, 8192);
    
    if (strpos($response, '200 OK') !== false) {
        echo "File exists on remote server";
    } else {
        echo "File does not exist on remote server";
    }
    
    fclose($fp);
}