PHP Function Reference

PHP stream_socket_recvfrom() Function



The PHP stream_socket_recvfrom() function is used to accept data from a remote socket up to length bytes.

Syntax

stream_socket_recvfrom(socket, length, flags, address)

Parameters

socket Required. Specify the remote socket.
length Required. Specify the number of bytes to receive from the socket.
flags Optional. The value of flags can be any combination of the following:
  • 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 Optional. If address is provided it will be populated with the address of the remote socket.

Return Value

Returns the read data, as a string

Example: stream_socket_recvfrom() example

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

<?php
//opening a server socket to port 1234 on localhost
$server = stream_socket_server('tcp://127.0.0.1:1234');

//accepting the connection
$socket = stream_socket_accept($server);

//accepting a packet (1500 is a typical MTU size) of OOB data
echo "Received Out-Of-Band: '"
     .stream_socket_recvfrom($socket, 1500, STREAM_OOB)."'\n";

//displaying the normal in-band data, but don't consume it
echo "Data: '".stream_socket_recvfrom($socket, 1500, STREAM_PEEK)."'\n";

//getting the exact same packet again, 
//but remove it from the buffer this time
echo "Data: '".stream_socket_recvfrom($socket, 1500)."'\n";

//closing it up
fclose($socket);
fclose($server);
?>

❮ PHP Streams Reference