Posted by: phillipnb | June 1, 2011

Network Programming in PHP


Network Programming is usually considered as the monopoly of computer programming languages like C,C plus plus or Java. PHP was never a favorite language among network programmers. Things have changed and today we have reached PHP version 5.3.x. PHP has come a long way in terms of its capabilities and it is capable of catering network programmers. Network and Socket programming in PHP are part of PHP Streams. Indeed you can write a client and server code using PHP streams as it has the ability for general file access to TCP and UDP sockets. Let us write a simple client and server using sockets to demonstrate the use of PHP Streams and Network Programming.

As we see in other programming languages, PHP too follows a series of steps to create a server. In case of the server code, we first create a socket, then bind it to a port and start listening for communications from some client. Once the server receives a message, it reads it, processes it and returns the response back to the concerned client. The client which is listening on that particular port receives the response.

Here is an example where we are going to create a client and server in which the server echoes back the received string (the string will be ‘reversed’) back to the client. The server code (server.php) in php is given below:

	$host = '127.0.0.1';
	$port = 1238;

	set_time_limit(0);

	$socketa    = socket_create(AF_INET,SOCK_STREAM,0) or die('Could not create a socket');
	$bResult    = socket_bind($socketa,$host,$port) or die('could not bind to port');
	$lResult    = socket_listen($socketa,3) or die('unable to listen');
	echo "\n Start listening...";
	$socketb    = socket_accept($socketa);
	$fromClient = socket_read($socketb,1024);
	$fromClient = trim($fromClient);
	$toClient   = strrev($fromClient);
	$writeLen   = socket_write($socketb,$toClient,strlen($toClient)) or die('unable to write');
	socket_close($socketa);
	socket_close($socketb);
	echo "\n Server shutting down..bye...";

Here is the code for our client (client.php)

	$host="127.0.0.1";
	$port = 1238;

	$message = "Hello World";

	$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("from Client: Could not create socket\n");
	$result = socket_connect($socket, $host, $port) or die("from Client: Unable to connect to server\n");
	socket_write($socket, $message, strlen($message)) or die("from Client: Unable to send data to server\n");
	$result = socket_read ($socket, 1024) or die("from client: Could not read response from server \n");
	socket_write($socket, "END", 3) or die("from client: Could not end session \n");
	socket_close($socket);
	$result = trim($result);
	echo "\n Message returned : ".$result;
	echo "\n Bye from Client...";

Let us dissect the client and server code line by line to understand it better:

socket_create(AF_INET,SOCK_STREAM,SOL_TCP);

Create a socket or endpoint for communication. The parameter AF_INET means IPv4 or Internet based protocols(TCP and UDP are common protocols of this IPv4 family). The parameter SOCK_STREAM provides sequenced, reliable, full-duplex, connection-based byte streams supporting a out-of-band data transmission mechanism. e.g. TCP. The last parameter sets the specific protocol within the specified domain to be used when communicating on the returned socket. In this case we are setting it as SOL_TCP.

socket_bind($socket,$host,$port);

Binds the name given in $host and $port to the socket described by $socket. This is done before a connection is established.

socket_listen($socket,3);

Listens for a incoming connection on a socket. The parameter ‘3’ tells the maximum of backlog incoming connections that will be queued for processing.

socket_connect($socket, $host, $port);

This initiates a connection to $host using the socket resource $socket.

socket_read ($socket, 1024);

Reads a maximum of length bytes from $socket. In this case 1024 bytes will be read.

socket_write($socket, "END", 3);

The function socket_write() writes to the socket from the given buffer (of certain length, in this the buffer is ‘END’ of length 3).

socket_close($socket);

socket_close() closes the socket resource given by $socket.

What we have seen so far is a basic example of client and server using php streams. Have fun by manipulating the code according to your imagination and requirements.

Till next time, Happy PHPing.

Advertisements

Responses

  1. Thank you very much for the break down of this huge topic!

  2. can you provide me the source code or the suggestions that how to establish a internet connection through Php

    • @Ranjana – I did not understand your question. PHP is a server side scripting language. When you try to establish an Internet connection , you are basically using a client to connect to the server that connects to the Internet, so I am not sure how PHP can be used as a client. BUT, if your question was to connect to a client within your internal network then get the ip of the device/machine that runs a server and try to connect to it.

  3. https://github.com/matyhtf/swoole . It is a php extension for php network server programing.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: