Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

PHP : Function Reference : Socket Functions : socket_select


Runs the select() system call on the given arrays of sockets with a specified timeout (PHP 4 >= 4.0.7, PHP 5)
int socket_select ( array &read, array &write, array &except, int tv_sec [, int tv_usec] )

socket_select() accepts arrays of sockets and waits for them to change status. Those coming with BSD sockets background will recognize that those socket resource arrays are in fact the so-called file descriptor sets. Three independent arrays of socket resources are watched.



The sockets listed in the read array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a socket resource is also ready on end-of-file, in which case a socket_read() will return a zero length string).


The sockets listed in the write array will be watched to see if a write will not block.


The sockets listed in the except array will be watched for exceptions.


The tv_sec and tv_usec together form the timeout parameter. The timeout is an upper bound on the amount of time elapsed before socket_select() return. tv_sec may be zero , causing socket_select() to return immediately. This is useful for polling. If tv_sec is NULL (no timeout), socket_select() can block indefinitely.


On exit, the arrays are modified to indicate which socket resource actually changed status.

You do not need to pass every array to socket_select(). You can leave it out and use an empty array or NULL instead. Also do not forget that those arrays are passed by reference and will be modified after socket_select() returns.


Due a limitation in the current Zend Engine it is not possible to pass a constant modifier like NULL directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:

Example 2297. Using NULL with socket_select()

socket_select($r, $w, $e, 0);

Return Values

On success socket_select() returns the number of socket resources contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens. On error FALSE is returned. The error code can be retrieved with socket_last_error().


Be sure to use the === operator when checking for an error. Since the socket_select() may return 0 the comparison with == would evaluate to TRUE:

Example 2298. Understanding socket_select()'s result

if (
false === socket_select($r, $w, $e, 0)) {
"socket_select() failed, reason: " .
socket_strerror(socket_last_error()) . "\n";


Example 2299. socket_select() example

/* Prepare the read array */
$read   = array($socket1, $socket2);
$write  = NULL;
$except = NULL;
$num_changed_sockets = socket_select($read, $write, $except, 0);

if (
$num_changed_sockets === false) {
/* Error handling */
} else if ($num_changed_sockets > 0) {
/* At least at one of the sockets something interesting happened */



Be aware that some socket implementations need to be handled very carefully. A few basic rules:

  • You should always try to use socket_select() without timeout. Your program should have nothing to do if there is no data available. Code that depends on timeouts is not usually portable and difficult to debug.
  • No socket resource must be added to any set if you do not intend to check its result after the socket_select() call, and respond appropriately. After socket_select() returns, all socket resources in all arrays must be checked. Any socket resource that is available for writing must be written to, and any socket resource available for reading must be read from.
  • If you read/write to a socket returns in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.
  • It's common to most socket implementations that the only exception caught with the except array is out-of-bound data received on a socket.

Code Examples / Notes » socket_select


The continuation of my my previous post on 28-Apr-2005 10:19 at
Here it is: (Link is broken into 2 parts)

ludvig dot ericson

Regarding the comment below, No, it does not, it's a system call and I believe it's rather hard to preserve keys.
Additionally, socket_select should be used like it was a user-inputted array, that you don't know what you sent in to.
$reads = $clients;
$reads[] = $server;
foreach ($reads as $read) {
   /* do some stuff */

calimero dot nospam

Please note that the timeout parameter has important side-effects on the CPU usage of your script.
Setting the timeout to 0 will make your CPU looping without any time to have some rest and handle other running processes on your system, causing the system load to increase heavily while your script is running.
Personnaly, I use a value of 15 ms for this parameter. this ensures a good listening frequency while letting your system load clear.
Example :
$read = array($ListeningSocket);
$num_changed_sockets = socket_select($read, $write = NULL, $except = NULL, 0, 10);
Hope this helps.


Note that the resulting arrays do NOT maintain keys (PHP 4.3.2) after being run through this function:
   [Client_Socket] => Resource id #6
   [Server_Socket] => Resource id #9
   [0] => Resource id #6
   [1] => Resource id #9
It would have been nice to have the keys stay to figure out which stream you need to receive from, but you'll have to use some fancy foreach loop to figure out which sockets to check.

richard neill

It is probably a bad idea to watch an array of sockets for input with socket_select, and then socket_read() using PHP_NORMAL_READ.
Although this seems desirable, you can end up with a permanently blocked program, if someone sends you malformed input which is missing a trailing \n \r. Guess how I found that out.

23-jan-2007 11:04

If you want to use a simple fractional value for timeout:
socket_select(..., floor($timeout), ceil($timeout*1000000));


If you haven't done any network programming before, PHP's socket_select() might appear a bit strange to you. I've written a simple php "partyline" script to demonstrate the multi-socket use of select'ing at

julian dot haupt

i just made a class which acts similiar to Perl's IO::Select in order to make socket selecting very easy
your script should look something like that:
$server = new Server;
$client = new Client;
for (;;) {
 foreach ($select->can_read(0) as $socket) {
   if ($socket == $client->socket) {
     // New Client Socket
   else {
     //there's something to read on $socket
you should of course implement some routines to detect broken sockets and remove them from the select object.
you can also do output buffering and check in the main-loop for sockets that are ready to write
class select {
 var $sockets;
 function select($sockets) {
   $this->sockets = array();
   foreach ($sockets as $socket) {
 function add($add_socket) {
 function remove($remove_socket) {
   $sockets = array();
   foreach ($this->sockets as $socket) {
     if($remove_socket != $socket)
       $sockets[] = $socket;
   $this->sockets = $sockets;
 function can_read($timeout) {
   $read = $this->sockets;
   socket_select($read,$write = NULL,$except = NULL,$timeout);
   return $read;
 function can_write($timeout) {
   $write = $this->sockets;
   socket_select($read = NULL,$write,$except = NULL,$timeout);
   return $write;


Another solution to the problem of keys not being preserved is to have an additional array for looking up sockets that uses their resource identifiers as keys. This can be obtained using array_flip() in some cases, but is particularly useful if each socket is associated with an object. In this case, you can make the object's constructor add a pointer to itself to the lookup array with its socket resource identifier as a key and use the following code to execute a read method for the object associated with each socket returned by socket_select():
socket_select($reads, $writes, $excepts, 0);
foreach ($sockets as $socket) {


A simple PHP script using socket_select() to manage multiple connections.
connect using "telnet localhost 9050". it broadcasts your messages that you send through telnet to other users connected to the server -- sort of like a chat script
$port = 9050;

// create a streaming socket, of type TCP/IP
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// set the option to reuse the port
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);

// "bind" the socket to the address to "localhost", on port $port
// so this means that all connections on this port are now our resposibility to send/recv data, disconnect, etc..
socket_bind($sock, 0, $port);

// start listen for connections
// create a list of all the clients that will be connected to us..
// add the listening socket to this list
$clients = array($sock);

while (true) {
// create a copy, so $clients doesn't get modified by socket_select()
$read = $clients;

// get a list of all the clients that have data to be read from
// if there are no clients with data, go to next iteration
if (socket_select($read, $write = NULL, $except = NULL, 0) < 1)

// check if there is a client trying to connect
if (in_array($sock, $read)) {
// accept the client, and add him to the $clients array
$clients[] = $newsock = socket_accept($sock);

// send the client a welcome message
socket_write($newsock, "no noobs, but ill make an exception :)\n".
"There are ".(count($clients) - 1)." client(s) connected to the server\n");

socket_getpeername($newsock, $ip);
echo "New client connected: {$ip}\n";

// remove the listening socket from the clients-with-data array
$key = array_search($sock, $read);

// loop through all the clients that have data to read from
foreach ($read as $read_sock) {
// read until newline or 1024 bytes
// socket_read while show errors when the client is disconnected, so silence the error messages
$data = @socket_read($read_sock, 1024, PHP_NORMAL_READ);

// check if the client is disconnected
if ($data === false) {
// remove client for $clients array
$key = array_search($read_sock, $clients);
echo "client disconnected.\n";
// continue to the next client to read from, if any

// trim off the trailing/beginning white spaces
$data = trim($data);

// check if there is any data after trimming off the spaces
if (!empty($data)) {

// send this to all the clients in the $clients array (except the first one, which is a listening socket)
foreach ($clients as $send_sock) {

// if its the listening sock or the client that we got the message from, go to the next one in the list
if ($send_sock == $sock || $send_sock == $read_sock)

// write the message to the client -- add a newline character to the end of the message
socket_write($send_sock, $data."\n");

} // end of broadcast foreach


} // end of reading foreach
// close the listening socket

Change Language

Follow Navioo On Twitter
eXTReMe Tracker