PHP stream_set_blocking() Function
The PHP stream_set_blocking() function sets blocking or non-blocking mode on a stream. This function works for any stream that supports non-blocking mode (currently, regular files and socket streams).
Syntax
stream_set_blocking(stream, enable)
Parameters
stream |
Required. Specify the stream. |
enable |
Required. If enable is false, the given stream will be switched to non-blocking mode, and if true, it will be switched to blocking mode. This affects calls like fgets() and fread() that read from the stream. In non-blocking mode an fgets() call will always return right away while in blocking mode it will wait for data to become available on the stream. |
Return Value
Returns true on success or false on failure.
Example:
The example below shows the usage of stream_set_blocking() function.
<?php $fp = fsockopen("www.example.com", 80); if (!$fp) { echo "Unable to open\n"; } else { fwrite($fp, "GET / HTTP/1.0\r\n\r\n"); stream_set_blocking($fp, true); $res = fread($fp, 1000); $info = stream_get_meta_data($fp); fclose($fp); if ($info['timed_out']) { echo 'Connection timed out!'; } else { echo $res; } } ?>
The output of the above code will be similar to:
HTTP/1.0 404 Not Found Content-Type: text/html Date: Sun, 24 Oct 2021 04:58:59 GMT Server: ECS (dna/63B4) Content-Length: 345 Connection: close <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>404 - Not Found</title> </head> <body> <h1>404 - Not Found</h1> </body> </html>
❮ PHP Streams Reference