How can stream_socket_client be used to make a POST request in PHP?

To make a POST request using stream_socket_client in PHP, you can create a stream context with the necessary options for the POST request, including the method, content type, and request body. Then, open a connection using stream_socket_client with the specified URL and context. Finally, write the POST data to the stream to send the request.

// Create stream context with POST data
$context = stream_context_create([
    'http' => [
        'method' => 'POST',
        'header' => 'Content-Type: application/x-www-form-urlencoded',
        'content' => http_build_query(['key1' => 'value1', 'key2' => 'value2'])
    ]
]);

// Open connection with stream_socket_client
$stream = stream_socket_client('http://example.com/api', $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);

// Write POST data to the stream
fwrite($stream, http_build_query(['key1' => 'value1', 'key2' => 'value2']));

// Read response
$response = stream_get_contents($stream);

// Close connection
fclose($stream);

// Output response
echo $response;