stream_socket_recvfrom()

stream_socket_recvfrom() — Receives data from a socket, connected or not.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

stream_socket_recvfrom() accepts data from a remote socket up to length bytes.

Signature

stream_socket_recvfrom(resource $socket, int $length, int $flags = 0, ?string &$address = null): string|false

Parameters

ParameterTypeWhat it takes
$socketresourceThe remote socket.
$lengthintThe number of bytes to receive from the socket.
$flagsintThe value of flags can be any combination of the following: Possible values for flags STREAM_OOB Process OOB (out-of-band) data. STREAM_PEEK Retrieve data from the socket, but do not consume the buffer. Subsequent calls to fread() or stream_socket_recvfrom() will see the same data.
&$address?stringIf address is provided it will be populated with the address of the remote socket.

Return value

Returns the read data, as a string, or false on failure.

Example

A runnable snippet:

/* Open a server socket to port 1234 on localhost */ $server = stream_socket_server('tcp://127.0.0.1:1234'); /* Accept a connection */ $socket = stream_socket_accept($server); /* Grab a packet (1500 is a typical MTU size) of OOB data */ echo "Received Out-Of-Band: '" . stream_socket_recvfrom($socket, 1500, STREAM_OOB) . "'\n"; /* Take a peek at the normal in-band data, but don't consume it. */ echo "Data: '" . stream_socket_recvfrom($socket, 1500, STREAM_PEEK) . "'\n"; /* Get the exact same packet again, but remove it from the buffer this time. */ echo "Data: '" . stream_socket_recvfrom($socket, 1500) . "'\n"; /* Close it up */ fclose($socket); fclose($server);

Changelog

VersionChange
8.0.0Now throws a ValueError if length is less than 1. Previously, an E_WARNING was raised and false was returned.

See also

stream_socket_sendto(), stream_socket_client(), stream_socket_server()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page stream_socket_recvfrom() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.