What are the potential pitfalls of using fsockopen in PHP to access password-protected content?

When using fsockopen in PHP to access password-protected content, one potential pitfall is that the username and password are sent in plain text, making them vulnerable to interception. To solve this issue, you can use HTTPS instead of HTTP to encrypt the communication between the client and server.

$host = 'example.com';
$port = 443; // HTTPS port
$path = '/protected-content';
$username = 'username';
$password = 'password';

$fp = fsockopen('ssl://' . $host, $port, $errno, $errstr, 30);
if (!$fp) {
    echo "Error: $errstr ($errno)<br>";
} else {
    $auth = base64_encode("$username:$password");
    $out = "GET $path HTTP/1.1\r\n";
    $out .= "Host: $host\r\n";
    $out .= "Authorization: Basic $auth\r\n";
    $out .= "Connection: Close\r\n\r\n";

    fwrite($fp, $out);

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

    fclose($fp);
}