What are the advantages of using stream_socket functions over fsockopen for handling HTTP POST requests in PHP?

When handling HTTP POST requests in PHP, using stream_socket functions offers more flexibility and control compared to fsockopen. Stream_socket functions allow for better error handling, support for SSL connections, and the ability to set custom headers and options easily. Additionally, stream_socket functions provide better performance and scalability for handling multiple requests simultaneously.

<?php
// Using stream_socket functions for handling HTTP POST requests
$host = 'example.com';
$port = 80;
$path = '/api';
$data = http_build_query(['key' => 'value']);

$fp = stream_socket_client("tcp://$host:$port", $errno, $errstr, 30);
if (!$fp) {
    echo "Error: $errstr ($errno)\n";
} else {
    $request = "POST $path HTTP/1.1\r\n";
    $request .= "Host: $host\r\n";
    $request .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $request .= "Content-Length: " . strlen($data) . "\r\n";
    $request .= "Connection: close\r\n\r\n";
    $request .= $data;

    fwrite($fp, $request);

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

    fclose($fp);
}
?>