Jul 25, 2008

Php Sockets - Introduction to an underused function of PHP

Free Web Hosting, No Ads > CONTRIBUTE > Tutorials

free web hosting

Php Sockets - Introduction to an underused function of PHP

HmmZ
This tutorial is based on a question written in the PHP programming board
Inspiration

Introduction
Sockets, an underused function in PHP, is a function that enables you to open connection to other peoples computers and vice versa. By sending commands to the operating server, it will first see if there's response, then, it sends or receives data that the operating server has available.

Creation of a socket
Of course, a first step in using sockets, is creating it, this is done by:

CODE
resource socket_create ( int domain, int type, int protocol)


and a more familiar seen example (php style):

CODE
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);


*The first parameter you see in the brackets, AF_INET is the domain. The PHP Manual states the following regarding domains, there are 2 domains:
QUOTE
AF_INET - IPv4 Internet based protocols. TCP and UDP are common protocols of this protocol family.
AF_UNIX - Local communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication).


AF_INET is the domain that is used for internet_based sockets, so you'll most likely be using this most often.

*The second parameter in the brackets, SOCK_STREAM is the type of socket, SOCK_STREAM is full duplex, meaning you can read ánd write to the socket.

*The last parameter in the brackets, SOL_TCP is the protocol, PHP knows 3 major protocols, icmp, udp and tcp[i], SOL_TCP is a constant protocol of TCP.

QUOTE
NOTE: You can also use getprotobyname("TCP"), or simply "0" instead of SOL_TCP,whatever rocks your boat.


Connection with a socket
You created the socket, now you need a connection to ultimately [i]use
it.

socket_connect is the function that enables you to connect to other computers using a socket, the syntax for this function:
CODE
bool socket_connect ( resource socket, string address [, int port])


The socket you created a few lines ago was assigned to the $socket variable, wich we can easily use in the socket connection syntax, now that we have both the create line aswell as the connection, we can connect to something, in this tutorial we will be connecting to an IRC server, on port 6667
NOTE: The port and irc server has been taken from an item i've read about sockets, since i don't have my own irc server, and this connection can be tested in reality
CODE
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
$connection = socket_connect($socket,'irc.freenode.net',6667);


Reading from a socket
Reading is of course an important element of sockets, as they are the actual interactivity with the client versus host, the socket_read() is the function that reads from a socket, the syntax for this function:
CODE
string socket_read ( resource socket, int length [, int type])


let's expand our current codes with this function:

CODE
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
$connection = socket_connect($socket,'irc.freenode.net',6667);
while($data = socket_read($socket,2046,PHP_NORMAL_READ))
//listen for any data, and echo that data out
{
echo $data;
}

NOTE: PHP_NORMAL_READ is a type of reading that will stop whenever the line terminates with a \r\n.

Writing to a socket
So far we made a socket, created a connection, and gave our script the socket_read() function. Now we need to reply to these readings with socket_write(). The syntax for this function:

CODE
int socket_write ( resource socket, string buffer [, int length])


Of course, the resource socket is the creation of the socket, wich was assigned to the $socket variable, the string buffer is simply what you want to write to the socket. let's add this to our existing code:

CODE
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); // Create the Socket
$connection = socket_connect($socket,'irc.freenode.net',6667); // Connect to freenode
socket_write($socket,"USER RHAP RHAP RHAP :RHAP\r\n"); // Send the Username to freenode
socket_write($socket,"NICK MyFirstSocket \r\n"); // Change our nickname
socket_write($socket,"JOIN #TEST \r\n"); // Join the channel PHPFREAKS!!!
while($data = socket_read($socket,2046)) // read whatever IRC is telling us
{
echo $data;
}

USER, NICK and JOIN are all irc commands that enable you to define the username, the nickname and what channel to join, in this example it's the channel #TEST, as you may have noticed, \r\n have been used, wich ends a line.

Listening for connections on your own computer
So far we created a socket, connected to a socket, written and read from a socket, now we are going to create a socket for users to connect and how to accept them when they try to connect, first we recreate our socket, no difference from the first socket creation:

CODE
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);


Now comes the difference, instead of connection to a socket, you bind it to your own machine, socket_bind() is our function, with as syntax:

CODE
bool socket_bind ( resource socket, string address [, int port])


as you can see, the parameters are pretty much the same as our other socket, just in a different function (socket_bind), let's translate this into PHP:

CODE
socket_bind($socket,'localhost',1111);


this binds the socket to the localhost on port 1111. A normal bind of course doesn't usually connect to localhost, so we'll replace that with a simple IP address: 111.111.111.111, the function would then look like this:

CODE
socket_bind($socket,'111.111.111.111',1111);


Now that you've bound your socket to your computer, let's listen from incoming connections, in this tutorial the way we're using the listen function can only accept 1 connection at a time. socket_listen() will listen and socket_accept can accept the connection. Let's add this to our socket code:

CODE
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // Create our socket.
socket_bind($socket,'111.111.111.111',1111); //bind the socket to our IP address, on port 1111.
socket_listen($socket); // listen for any incoming connections
while($connection = socket_accept($socket)) // accept any incoming connection and write to the socket.
{
socket_write($connection,'You\'ve successfully connected to my computer!\r\n');
}


in this code, the socket listens for connections and once it detects one, it will send 'You've successfully connected to my computer' to the socket.

Try it with your own IP on port 1111 happy.gif.



That concludes an introduction in PHP Sockets, the socket you just made, connected to, bound to, listened to, read and wrote to, is basically an IRC Bot (don't worry it's nothing illegal tongue.gif).
Anyway, I hoped this would make you understand a bit about what sockets do and how they are used in PHP, an IRC bot is just an example of what a socket can do. Feel free to experiment and see what comes out, you never know what great things you come up with smile.gif

I hope this helped you a bit.


 

 

 


Reply

HmmZ
Any feedback? ohmy.gif

Reply

Takeshi
Nice tutorial. I agree that it is an underused feature. An even more underused feature is "command-line php" which can be used to create server and other applications under *nix console.

PHP isn't just a web scripting language. Its a full-blown programming language.

Reply

ausnrl
Seems quite interesting il try it one day!!!! smile.gif

Reply

marcp
That's a great tutorial! Thanks.

I've been trying to make a PHP ping function. The problem I have is that Windows doesn't give PHP permission to use raw sockets. Do you know if there's a way to allow PHP to use ICMP? Or is there another way I can check to see if a system is up/down via PHP?

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Recent Queries:-
  1. php sockets - 108.59 hr back. (1)
Similar Topics

Keywords : php sockets introduction underused function php

  1. Php - Forms, Date And Include - Working with POST and GET and also the Date() function (0)
  2. User Permission Function [php] - Determining User Permissions (3)
    There have been several recent request for methods to restrict access to various pages on a web-site
    based on User Permissions in sites that have a Login System in place. Here is some code showing one
    method to restrict access by providing a sub-set of your site's links based on the User's
    permissions. In this demonstration, I have defined a string for each 'level of user'
    determining which set(s) of links they can view on your site. Normal MySql procedure would be to
    read the User's permission level from a record in the database. For the purpose of ...
  3. Delphi - Simple Text Parsing Function (1)
    Because parsing is such an integral part of string manipulation, I took the time to make a quick and
    simple parse function. For you VBers, Delphi is a derivative of Pascal...it's powerful, simple,
    and (best of all) doesn't need external component (eg: ocx files). Hence the code: Code:
    function TForm1.SimpleParse(MainString, BeginString, EndString: string): string; var PosBeginString:
    integer; PosEndString: integer; begin PosBeginString := Pos(BeginString, MainString) +
    Length(BeginString); PosEndString := Pos(EndString, MainString); Result := Copy(MainString, ...
  4. How To Make A Proper Introduction - Not just: Hi, I am here. (7)
    How to make a proper introduction to Trap17 forum members. FIRST OF ALL READ THE TRAP 17
    FORUM RULES AND REGULATIONS Basic Rules In-depth Regulations Trap 17 has these
    rules and regulations to maintain some kind of order in this chaotic world; to keep the forum
    refreshing and informative, uncluttered by useless, redundant chatter. PLEASE follow them. After
    all this is all for FREE and keeps Trap 17 up and running. Who are you? (You
    needn't use your legal name, but give us something to call you that is an indicator of you...
  5. A Little Introduction To 3d Studio Max - How to make a simple abstract image (9)
    This tutorial will teach you the basics of making abstract images in 3D studio max. In this example,
    I used a simple sphere, and applied the “Noise” modifier. Then, I applied a transparent, blue,
    plastic-like material to spice up the whole thing. Let’s start. First, make a sphere by selecting
    the “Sphere” button in the “Standard Primitives” section, and draw somewhere in the center of the
    perspective view. We will set the size of the sphere later on. The sphere I made looks like this,
    yours can be different in size and color, but the only thing that is important is to...
  6. Php - Randomize Web Title - using arrays and the random function (5)
    PHP - Randomize Web Title with the rand function... Define the variables numbers we start at number
    0 CODE <?php $title[0] = "Web title 0"; // Title 0
    $title[1] = "Web title 1"; // Title 1 $title[2] = "Web title
    2"; // Title 2 $title[3] = "Web title 3"; // Title 3
    $title[4] = "Web title 4"; // Title 4 ?> now we use the rand()
    function to get a randomize the web title. rand(0, 4) means we start at 0 and end at 4 i can get
    0,1,2,3,4 one of those. ...
  7. Introduction To Templating - Templating your website with PHP (1)
    Pre-note Hello and welcome. if your website doesn't use a templating function, you may have
    noticed it's pretty hard to update your website (layout) unless you dig through many files to
    update the images and such. The solution is templates. If you ever got curious and looked into
    phpBB codes or any other template based forum/CMS, you saw the .tpl files they use. I am not at a
    point where i base everything on .tpl (simply because i havent taken the time to see how it all
    works). But i do can tell you that it's the same principle, template your site using an...
  8. An Introduction To Java And Graphics - (5)
    Table of Contents I. Introduction II. Before You Begin III. Necessities in a Java Program IV.
    Creating a Canvas V. Shapes A. Line B. Rectangle C. Oval D. Polygon VI. Other Things A.
    Changing the Color B. Strings 1. Changing the Font 2. Drawing a String C. Images VII.
    Conclusion I. Introduction Welcome to my second tutorial here at Trap17. I'm going on
    vacation for a week so I thought I'd leave you all with some of the things that I picked up in
    the class I took ealier this summer. If anyone wants to see some things that I've done, t...
  9. Using The Date() Function [php] - (2)
    The date() function can be used in a good way, in some cases, and the most common place you would
    probably see this in use would be on forums. Let's get down to business... If you would like to
    display the date, you would have to put the echo tag before the date() function as so... CODE
    echo date("g:i:s"); Which would display as the common hours, minutes,
    seconds format (ex: 3:32:45). But you can also add wheather it is AM or PM, display the day (Sunday
    thru Monday), the year, pretty much anything that has to do with date. Here is a...
  10. [tutorial] Delphi - Multi-Parsing Function (0)
    I've spent a while trying to create parsing function with Delphi. This language is very useful.
    This tutorial explains how to parse multiple instances of an item in one string. Here is the
    function (which I am actually very proud of): Code: function TForm1.MultiParse(MainString,
    BeginString, EndString: string): TStrings; var PosBeginString, PosEndString, i, LastPos: integer;
    tmpCopy: string; tmpStrings: TStrings; begin tmpStrings := TStringList.Create; LastPos := 0;
    for i := 1 to LastDelimiter(EndString, MainString) do begin PosBeginString := Pos...



Looking for php, sockets, introduction, underused, function, php

Searching Video's for php, sockets, introduction, underused, function, php
advertisement



Php Sockets - Introduction to an underused function of PHP



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE