How can the fsockopen function be used to establish a connection to a website in PHP?

To establish a connection to a website using the fsockopen function in PHP, you need to specify the host and port to connect to. This function allows you to create a socket connection to the specified host and port, which can be useful for tasks like sending HTTP requests or fetching data from a remote server.

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

$fp = fsockopen($host, $port, $errno, $errstr, 30);
if (!$fp) {
    echo "Error: $errstr ($errno)\n";
} else {
    fwrite($fp, "GET / HTTP/1.0\r\nHost: $host\r\n\r\n");
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}