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.

Syntax

stream_set_timeout(stream, seconds, microseconds)

Parameters

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.

Example:

The example below shows the usage of stream_set_timeout() 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_timeout($fp, 2);
  $res = fread($fp, 500);

  $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 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"
         "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

5