How can stream_set_timeout be used in PHP scripts that utilize fsockopen for server communication?
When using fsockopen for server communication in PHP scripts, it is important to set a timeout to prevent the script from hanging indefinitely if the server does not respond. This can be achieved by using the stream_set_timeout function to specify a maximum time for the script to wait for a response from the server before timing out.
// Open a connection to the server
$socket = fsockopen('example.com', 80, $errno, $errstr, 30);
// Set a timeout of 10 seconds for the socket
stream_set_timeout($socket, 10);
// Send a request to the server
fwrite($socket, "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
// Read the response from the server
$response = fread($socket, 4096);
// Close the connection
fclose($socket);