How can the return value of fgets be utilized to improve error handling and data retrieval in a TcpSocket connection in PHP?

When reading data from a TcpSocket connection in PHP using fgets, the return value of fgets can be utilized to improve error handling and data retrieval. By checking the return value of fgets, we can detect if an error occurred or if the connection was closed. This allows us to handle these cases appropriately and prevent unexpected behavior in our application.

$socket = stream_socket_client('tcp://example.com:80', $errno, $errstr, 30);

if (!$socket) {
    echo "Error opening socket: $errstr ($errno)\n";
    exit;
}

$data = fgets($socket);

if ($data === false) {
    echo "Error reading data from socket\n";
    fclose($socket);
    exit;
}

echo "Data received from socket: $data\n";

fclose($socket);