In what scenarios would it be more appropriate to use fsockopen over other methods for retrieving files from a web server in PHP?

fsockopen is more appropriate than other methods for retrieving files from a web server in PHP when you need more control over the connection, such as setting custom headers, handling redirects, or working with non-standard protocols. It allows for lower-level socket operations, making it suitable for advanced networking tasks.

<?php
$host = 'www.example.com';
$port = 80;
$path = '/file.txt';

$fp = fsockopen($host, $port, $errno, $errstr, 30);
if (!$fp) {
    echo "Error: $errstr ($errno)\n";
} else {
    $out = "GET $path HTTP/1.1\r\n";
    $out .= "Host: $host\r\n";
    $out .= "Connection: Close\r\n\r\n";

    fwrite($fp, $out);

    while (!feof($fp)) {
        echo fgets($fp, 128);
    }

    fclose($fp);
}
?>