PHP Function Reference

PHP stream_set_timeout() Function

The PHP stream_set_timeout() function sets the timeout value on the given stream, expressed in the sum of seconds and microseconds.

When the stream times out, the 'timed_out' key of the array returned by stream_get_meta_data() is set to true, although no error/warning is generated.


stream_set_timeout(stream, seconds, microseconds)


stream Required. Specify the target stream.
seconds Required. Specify the seconds part of the timeout to be set.
microseconds Optional. Specify the microseconds part of the timeout to be set. Default is 0.

Return Value

Returns true on success or false on failure.


The example below shows the usage of stream_set_timeout() function.

$fp = fsockopen("", 80);
if (!$fp) {
  echo "Unable to open\n";
} else {
  fwrite($fp, "GET / HTTP/1.0\r\n\r\n");
  stream_set_timeout($fp, 2);
  $res = fread($fp, 500);

  $info = stream_get_meta_data($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 05:01:00 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"
<html xmlns="" xml:lang="en" lang="en">
        <title>404 - Not Found</title>
        <h1>404 - Not Found</h1>

❮ PHP Streams Reference