How can the fsockopen function be used effectively in PHP to connect to a web server and retrieve specific files?

To effectively use the fsockopen function in PHP to connect to a web server and retrieve specific files, you need to provide the server's hostname, port number, and the specific file path you want to retrieve. You can then use fsockopen to establish a connection to the server, send an HTTP request for the specific file, and read the response to retrieve the file content.

$host = 'example.com';
$port = 80;
$path = '/specific/file.html';

$fp = fsockopen($host, $port, $errno, $errstr, 30);
if (!$fp) {
    echo "Error: $errstr ($errno)";
} else {
    $out = "GET $path HTTP/1.1\r\n";
    $out .= "Host: $host\r\n";
    $out .= "Connection: Close\r\n\r\n";

    fwrite($fp, $out);

    $response = '';
    while (!feof($fp)) {
        $response .= fgets($fp, 128);
    }

    fclose($fp);

    // Process $response to retrieve the file content
    echo $response;
}