How can fsockopen be used to send POST data to another server in PHP?

To send POST data to another server using fsockopen in PHP, you can open a connection to the server, set the necessary headers for a POST request, and then send the data using fwrite. This allows you to programmatically send data to another server without relying on cURL or other libraries.

$host = 'www.example.com';
$port = 80;
$path = '/submit.php';
$data = 'key1=value1&key2=value2';

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

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