How can non-blocking sockets be implemented in PHP to prevent script blocking during fwrite operations?

Non-blocking sockets can be implemented in PHP using the stream_set_blocking() function to set the socket to non-blocking mode. This prevents the script from blocking during fwrite operations by allowing the script to continue execution while waiting for the socket to be ready for writing.

$socket = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30);
stream_set_blocking($socket, 0);

if ($socket === false) {
    echo "Error connecting to socket: $errstr ($errno)";
} else {
    fwrite($socket, "GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n");
    fclose($socket);
}