What is the purpose of using fsockopen and fread in PHP for socket connections?

fsockopen is used in PHP to establish a socket connection to a specified host and port. Once the connection is established, fread can be used to read data from the socket. This combination of functions allows for communication with servers or other systems over a network using TCP or UDP protocols.

$socket = fsockopen("example.com", 80, $errno, $errstr, 30);
if (!$socket) {
    echo "Error: $errstr ($errno)\n";
} else {
    fwrite($socket, "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n");
    
    while (!feof($socket)) {
        echo fread($socket, 1024);
    }
    
    fclose($socket);
}