W3docs

PHP socket_set_timeout() Function: Everything You Need to Know

As a PHP developer, you may need to set a timeout for a socket to avoid lengthy waits and potential resource waste. The socket_set_timeout() function is a

When your script reads from a network connection, a slow or dead server can leave PHP blocking indefinitely, tying up a worker and frustrating users. The socket_set_timeout() function sets a deadline on read/write operations so a stalled connection fails fast instead of hanging. This article explains exactly what it controls, the common pitfalls, and how to detect a timeout when one happens.

What the socket_set_timeout() Function Does

socket_set_timeout() sets the timeout for I/O operationsfread(), fgets(), fwrite(), etc. — on a stream opened with fsockopen() or pfsockopen(). If a read or write does not complete within the deadline, the operation returns early and the stream is flagged as timed out.

Two things it does not do:

  • It does not affect the connection timeout. That is the fifth argument to fsockopen($host, $port, $errno, $errstr, $connectTimeout). socket_set_timeout() only governs data transfer after the connection is open.
  • It does not make the call fail loudly. A read that times out returns the data received so far (often an empty string) and sets a flag — you have to inspect that flag yourself with stream_get_meta_data().

Naming trap: Despite the socket_ prefix, this function belongs to the streams family, not the Sockets extension. It works on resources from fsockopen(), never on a resource from socket_create(). Since PHP 8.0 it is a deprecated alias of stream_set_timeout() — prefer that name in new code.

Syntax

socket_set_timeout(resource $stream, int $seconds, int $microseconds = 0): bool
ParameterDescription
$streamAn open stream resource returned by fsockopen() or pfsockopen().
$secondsThe timeout in whole seconds.
$microsecondsAdditional time in microseconds (optional, default 0).

It returns true on success and false on failure (for example, if $stream is not a valid stream resource).

A Working Example

Open a connection, set a 5-second read timeout, then ask whether a read timed out:

<?php

// Open a TCP connection to a web server.
$stream = fsockopen("www.example.com", 80, $errno, $errstr, 10);

if (!$stream) {
    echo "Connection failed: $errstr ($errno)\n";
    exit;
}

// Fail any single read/write that stalls for more than 5 seconds.
socket_set_timeout($stream, 5);

// Send a minimal HTTP request.
fwrite($stream, "GET / HTTP/1.0\r\nHost: www.example.com\r\n\r\n");

// Read the first line of the response.
$line = fgets($stream, 1024);

// Check whether that read hit the timeout.
$info = stream_get_meta_data($stream);

if ($info['timed_out']) {
    echo "Read timed out — the server was too slow.\n";
} else {
    echo "First response line: " . trim($line) . "\n";
}

fclose($stream);

The key is the stream_get_meta_data() call: its timed_out element is the only reliable way to tell a genuine timeout apart from a connection that simply closed.

Reading in a Loop

When you read a whole response, check timed_out on every iteration so a mid-transfer stall does not silently truncate your data:

<?php

$stream = fsockopen("www.example.com", 80, $errno, $errstr, 10);
socket_set_timeout($stream, 5);

fwrite($stream, "GET / HTTP/1.0\r\nHost: www.example.com\r\n\r\n");

$body = "";
while (!feof($stream)) {
    $chunk = fgets($stream, 4096);
    $info  = stream_get_meta_data($stream);

    if ($info['timed_out']) {
        echo "Stalled before the response finished.\n";
        break;
    }
    $body .= $chunk;
}

fclose($stream);
echo "Received " . strlen($body) . " bytes.\n";

Common Pitfalls

  • Wrong resource type. Passing a socket_create() resource does nothing useful — use stream_set_timeout() with socket_create() sockets, or socket_set_option() for SO_RCVTIMEO/SO_SNDTIMEO.
  • Confusing connect and read timeouts. A long fsockopen() connect timeout will not save you from a slow response; you need both.
  • Forgetting to check timed_out. Without it, a timed-out read looks exactly like a clean end of stream, leading to silently truncated data.

Conclusion

socket_set_timeout() keeps slow network reads and writes from hanging your PHP script. Remember that it works on fsockopen() streams (not the Sockets extension), governs I/O rather than the connection, and that you must inspect stream_get_meta_data()'s timed_out flag to know a timeout actually occurred. In new code, reach for its modern name, stream_set_timeout().

Practice

Practice
What does the socket_set_timeout() function in PHP do?
What does the socket_set_timeout() function in PHP do?
Was this page helpful?