In what scenarios would it be more appropriate to use fsockopen instead of fopen in PHP for server communication?

When you need to establish a network connection to a server and send/receive data over that connection, it would be more appropriate to use fsockopen instead of fopen in PHP. This is because fsockopen allows for more control over the connection, such as setting timeouts and handling errors more effectively.

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

$socket = fsockopen($host, $port, $errno, $errstr, 30);

if (!$socket) {
    echo "Error: $errstr ($errno)\n";
} else {
    fwrite($socket, "GET / HTTP/1.1\r\nHost: $host\r\nConnection: close\r\n\r\n");

    while (!feof($socket)) {
        echo fgets($socket, 4096);
    }

    fclose($socket);
}