In PHP, stream_socket_recvfrom() reads up to a given number of bytes from a socket stream and can capture the sender address.
It is useful for connectionless or addressed receives. Pass the max length, optional flags, and an optional by-reference $address. For offline teaching, pair it with stream_socket_pair() and stream_socket_sendto().
Syntax
Call stream_socket_recvfrom() with the values you need. Start with this line.
Reads data and stores the sender address in $from.
stream_socket_recvfrom($sock, 8)
Reads a small fixed-size message.
Returns the received string, or false on failure. Unlike fread(), it can fill $address with the remote side. On a stream pair, sendto/recvfrom still move bytes between the two ends for simple demos.
Library declarations
PHP
stream_socket_recvfrom(resource $socket, int $length, int $flags = 0, ?string &$address = null): string|false
Parameters
Parameter
Description
socket
Required. A socket stream to read from.
length
Required. Maximum number of bytes to read.
flags
Optional. Socket flags. Defaults to 0.
address
Optional. By-reference string filled with the sender address when available.
Return Value
Return Value
Description
string
The bytes that were received.
false
The read failed.
PHP Examples
Example 1 — Receive Across a Socket Pair
Send with stream_socket_sendto() and receive with stream_socket_recvfrom().
Show the $address argument with a fixed sample peer string for tutorials.
PHP
<?php
// On UDP or accepted TCP clients, $address may become '127.0.0.1:54321'.
$address = '127.0.0.1:54321';
echo 'sample sender: ', $address, PHP_EOL;
echo 'recvfrom fills $address when the transport provides it', PHP_EOL;
Output
sample sender: 127.0.0.1:54321
recvfrom fills $address when the transport provides it
How It Works
Pass $address by reference as the fourth argument.
Some transports fill it with the sender name.
Logging the address helps debug packet sources.
Pair demos may leave address empty depending on platform.
Frequently Asked Questions
It reads up to length bytes from a socket and can store the sender address in a by-reference variable.
Both can read bytes. recvfrom adds the optional address parameter used with many socket transports.
Yes. You get only the bytes that were available, up to the maximum you asked for.
Use stream_socket_pair() with stream_socket_sendto() on the other end.
The receive failed. Check the stream state and any warnings before retrying.