In what situations would using fsockopen be preferred over Curl for sending data in PHP?

fsockopen would be preferred over Curl for sending data in PHP when you need more control over the network connection, such as setting specific headers or customizing the request in a more detailed manner. Additionally, fsockopen can be useful when you need to work with protocols other than HTTP, such as FTP or SMTP.

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

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

if (!$socket) {
    echo "Error: $errstr ($errno)\n";
} else {
    $data = "GET / HTTP/1.1\r\n";
    $data .= "Host: $host\r\n";
    $data .= "Connection: close\r\n\r\n";

    fwrite($socket, $data);

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

    fclose($socket);
}