How can one differentiate between a valid response and a 404 error page when using fsockopen to fetch URLs in PHP?

When using fsockopen to fetch URLs in PHP, one can differentiate between a valid response and a 404 error page by checking the HTTP status code returned in the response headers. A 404 error page will have a status code of 404, indicating that the requested resource was not found. By checking the status code, one can determine if the response is valid or if an error occurred.

$fp = fsockopen('www.example.com', 80, $errno, $errstr, 30);
if (!$fp) {
    echo "Error: $errstr ($errno)";
} else {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: www.example.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    
    $response = '';
    while (!feof($fp)) {
        $response .= fgets($fp, 128);
    }
    
    $status_code = substr($response, 9, 3);
    
    if ($status_code == 404) {
        echo "404 Error: Page not found";
    } else {
        echo "Valid response received";
    }
    
    fclose($fp);
}