AJAX is a SEO Friend…….
Ajax is a SEO friendly tech……
Solution will be given after your comments and suggestions.
Regards,
Albert
Please SAVE OUR INDIA
Dear Friends,
U CAN MAKE A HUGE DIFFERENCE TO THE INDIAN ECONOMY BY FOLLOWING FEW SIMPLE STEPS.
Please spare a couple of minutes here… for the sake of India … our country.
I got this article from one of my friends, but it’s true, I can see this in day to day life,
Small example,
Before 5 months 1 US $ = IND Rs 39
After 5 months. Now it is 1 $ = IND Rs 50
Do you think US Economy is booming? No, but Indian Economy is Going Down.
Our Economy is in u’r hands
INDIAN economy is in a crisis. Our country like many other ASIAN countries is undergoing a severe economic crunch. Many INDIAN industries are closing down. The INDIAN economy is in a crisis and if we do not take proper steps to control those, we will be in a critical situation.
More than 30000 crore rupees of foreign exchange are being siphoned out of our country on products such as cosmetics, snacks, tea, beverages… etc which are grown, produced and consumed here.
A cold drink that costs only 70 / 80 paisa to produce is sold for NINE rupees, and a major chunk of profits from these are sent abroad. This is a serious drain on INDIAN economy.
We have nothing against Multinational companies, but to protect our own interests we request everybody to use INDIAN products only for next two years. With the rise in petrol prices, if we do not do this, the rupee will devalue further and we will end up paying much more for the same products in the near future.
What you can do about it?
1. Buy only products manufactured by WHOLLY INDIAN COMPANIES.
2. ENROLL as many people as possible for this cause.
Each individual should become a leader for this awareness.
This is the only way to save our country from severe economic crisis. You don’t need to give-up your lifestyle. You just need to choose an alternate product.
All categories of products are available from WHOLLY INDIAN COMPANIES.
LIST OF PRODUCTS
COLD DRINKS:
USE: – LEMON JUICE, FRESH FRUIT JUICES, CHILLED LASSI (SWEET OR SOUR), BUTTER MILK, COCONUT WATER, JALJEERA, ENERJEE, and MASALA MILK…
INSTEAD OF: -
COCA COLA, PEPSI, LIMCA, MIRINDA, SPRITE
BATHING SOAP:
USE – CINTHOL & OTHER GODREJ BRANDS, SANTOOR, WIPRO SHIKAKAI, MYSORE SANDAL, MARGO, NEEM, EVITA, MEDIMIX, GANGA , NIRMA BATH & CHANDRIKA
INSTEAD OF – LUX, LIFEBOY, REXONA, LIRIL, DOVE, PEARS, HAMAM, LESANCY, CAMAY, PALMOLIVE
TOOTH PASTE: -
USE – NEEM, BABOOL, PROMISE, VICO VAJRADANTI, PRUDENT, DABUR PRODUCTS, MISWAK
INSTEAD OF – COLGATE, CLOSE UP, PEPSODENT, CIBACA, FORHANS, MENTADENT.
TOOTH BRUSH: -
USE – PRUDENT, AJANTA , PROMISE
INSTEAD OF – COLGATE, CLOSE UP, PEPSODENT, FORHANS, ORAL-B
SHAVING CREAM:
USE – GODREJ, EMANI
INSTEAD OF – PALMOLIVE, OLD SPICE, GILLETE
BLADE:-
USE – SUPERMAX, TOPAZ, LAZER, ASHOKA
INSTEAD OF – SEVEN-O -CLOCK, 365, GILLETTE
TALCUM POWDER:
USE – SANTOOR, GOKUL, CINTHOL, WIPRO BABY POWDER, BOROPLUS
INSTEAD OF – PONDS, OLD SPICE, JOHNSON BABY POWDER, SHOWER TO SHOWER
MILK POWDER:
USE – INDIANA, AMUL, AMULYA
INSTEAD OF – ANIKSPRAY, MILKANA, EVERYDAY MILK, MILKMAID.
SHAMPOO:
USE – LAKME, NIRMA, VELVET
INSTEAD OF – HALO, ALL CLEAR, NYLE, SUNSILK, HEAD AND SHOULDERS, PANTENE
MOBILE CONNECTIONS:
USE – BSNL, AIRTEL
INSTEAD OF – HUTCH
Every INDIAN product you buy makes a big difference. It saves INDIA . Let us take a firm decision today.
BUY INDIAN TO BE INDIAN we are not against of foreign products.
WE ARE NOT ANTI-MULTINATIONAL.
WE ARE TRYING TO SAVE OUR NATION. EVERY DAY IS A STRUGGLE FOR A REAL FREEDOM.
WE ACHIEVED OUR INDEPENDENCE AFTER LOSING MANY LIVES.
THEY DIED PAINFULLY TO ENSURE THAT WE LIVE PEACEFULLY. THE CURRENT TREND IS VERY THREATENING.
MULTINATIONALS CALL IT GLOBALISATION OF INDIAN ECONOMY. FOR INDIANS LIKE YOU AND ME IT IS RECOLONISATION OF INDIA …
THE COLONIST’S LEFT INDIA THEN. BUT THIS TIME THEY WILL MAKE SURE THEY DON’T MAKE ANY MISTAKES.
WHO WOULD LIKE TO LET A” GOOSE THAT LAYS GOLDEN EGGS” SLIP AWAY.
PLEASE REMEMBER: POLITICAL FREEDOM IS USELESS WITHOUT ECONOMIC INDEPENDENCE .
RUSSIA , S.KOREA , MEXICO ……….THE LIST IS VERY LONG!!
LET US LEARN FROM THEIR EXPERIENCE AND FROM OUR HISTORY.
LET US DO THE DUTY OF EVERY TRUE INDIAN.
FINALLY: IT’S OBVIOUS THAT U CAN’T GIVE UP ALL OF THE ITEMS MENTIONED ABOVE,
SO GIVE UP ATLEAST ONE ITEM TO FOR THE SAKE OF OUR COUNTRY.
We would be sending useless forwards to our friends daily.
Instead please forward this mail to all your friends to create awareness.
“LITTLE DROPS MAKE A GREAT OCEAN “
SAVE INDIA , SAVE INDIAN ECONOMY FOR THE BETTER FUTURE …….
Socket programming using perl with interaction
Client Program.
#!/usr/bin/perl -w
# serIO.pl
# Client Program
#———————
use strict;
use IO::Socket;
use Sys::Hostname;
print “>> Client Program <<\n\n”;
# Create a new socket
my $sock = new IO::Socket::INET(
PeerAddr => ‘localhost’,
PeerPort => 4587,
Proto => ‘tcp’);
#Check for connection
$sock or die “no socket :$!”;
#print username
print “Enter the username : “;
#get the value for username
chop (my $username = <STDIN>);
#send username to the server
print $sock “USERNAME,”,$username,”\n”;
#get the reply from the server
my $usernameFlag = scalar <$sock>;
if ( $usernameFlag == “1″ )
{
print “Enter the password : “;
chop (my $password = <STDIN>);
print $sock “PASSWORD,”,$password,”\n”;
my $passwordFlag = scalar <$sock>;
if ( $passwordFlag == “1″ ) {
print “START POSTING DATA\n”;
my $def_msg = “Enter data to be sent : “;
print $def_msg;
my $data = “\n”;
while($data)
{
chop (my $data = <STDIN>);
if ( ($data eq “exit”) ) {
print $sock “exit”,”\n”;
print scalar <$sock>,”\nYou have exited from sending messages\n”;
exit 1;
}
if ( $data ne “” ) {
print $sock “DATA,”,$data,”\n”;
my $dataFlag = scalar <$sock>;
print $dataFlag;
}
print $def_msg;
}
}
else
{
print “Sorry, wrong password.\n”;
}
}
else
{
print “Sorry, wrong username.\n”;
exit 1;
}
#print $username;
exit;
That’s NOT MY JOB!!!
Now this is what we call as “Out of scope”……………….
Presenting THIS YEAR’S “Not My Job” AWARD
And the winner is
INDIAN National Highway Department (Painting Division)
Socket Programming Using PERL
Socket Programming in PERL – Types of Sockets
There are just two types of sockets: connection oriented and connection-less. There are other types but this classification is fair enough to get started, a socket has a domain (UNIX or internet), a connection type (connection oriented or connection less) and a protocol (TCP or UDP).
A connection oriented or a stream socket is a reliable two way communication. If you send three packets, say 1, 2 and 3, they are received in the same order they were sent. They achieve this high level of transmission quality by using TCP for error free reliable communication. The ubiquitous telnet application uses stream sockets.
The connection-less sockets or stream-less sockets use IP for routing but use the UDP. They are connectionless, since the connection need not be open as in stream sockets, the packet formed is given a destination IP address and than transmitted. This method is mostly used for packet-to-packet transfer as in ftp applications.
How a Packet is Formed
We will use an example of UDP packet for some light stuff on networking theory. It’s Data Encapsulation. A packet is formed by encapsulating the data in a header at each level as it passes through the layers (protocol stack). At the receiving end the headers are stripped off as the packet travels up the layers to get the data.
Basically, at each layer, the protocol adds a header to the payload to perform the required functionality.
Client Server Architecture
It’s a client-server world, today. Just about everything on the network deals with client processes talking to server processes and vice versa. Take the ubiquitous telnet, for instance. When you connect to a remote host on port 23 with telnet (the client), a program on that host (called telnetd, the server) springs to life. It handles the incoming telnet connection, sets up a login prompt, etc. Note that the client-server pair can speak in streaming or stream-less, or anything else (as long as they are speaking the same thing).
Some good examples of client-server pairs are telnet/telnetd, ftp/ftpd.
Socket Programming in PERL – Client–Server Script in PERL
Comfortable so far? Let’s dive head-first in to coding a simple client server interaction in PERL. Client/server network programming requires a server running on one machine to serve one or more clients running on either the same machine or different machines. These different machines can be located anywhere on the network.
To create a server, simply perform the following steps using the built-in Perl function indicated:
Create a socket with socket.
Bind the socket to a port address with bind.
Listen to the socket at the port address with listen.
Accept client connections with accept.
Establishing a client is even easier:
Create a socket with socket.
Connect (the socket) to the remote machine with connect.
A Simple Server
1. #! /usr/bin/perl -w
2. # server0.pl
3. #——————–
4. use strict;
5. use Socket;
6. # use port 7890 as default
7. my $port = shift || 7890;
8. my $proto = getprotobyname(‘tcp’);
9. # create a socket, make it reusable
10. socket(SERVER, PF_INET, SOCK_STREAM, $proto) or die “socket: $!”;
11. setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1) or die “setsock: $!”;
12. # grab a port on this machine
13. my $paddr = sockaddr_in($port, INADDR_ANY);
14. # bind to a port, then listen
15. bind(SERVER, $paddr) or die “bind: $!”;
16. listen(SERVER, SOMAXCONN) or die “listen: $!”;
17. print “SERVER started on port $port “;
18. # accepting a connection
19. my $client_addr;
20. while ($client_addr = accept(CLIENT, SERVER))
21. {
22. # find out who connected
23. my ($client_port, $client_ip) = sockaddr_in($client_addr);
24. my $client_ipnum = inet_ntoa($client_ip);
25. my $client_host = gethostbyaddr($client_ip, AF_INET);
26. # print who has connected
27. print “got a connection from: $client_host”,”[$client_ipnum] “;
28. # send them a message, close connection
29. print CLIENT “Smile from the server”;
30. close CLIENT;
31. }
Analysis
This simple server can run just on one machine that can service only one client program at a time connecting from the same or a different machine. Recall that the steps for creating a server were to create a socket, bind it to a port, listen at the port and accept client connections.
Line 1 and 4
It is generally a good idea to compile a Perl script using strict. This requires all variables to be declared with the “my” function before they are used. Using “my” may be inconvenient, but it can catch many common syntactically correct yet logically incorrect programming bugs.
Line 7
The variable $port is assigned the first command-line argument or port 7890 as the default. When choosing a port for your server, pick one that is unused on your machine.
Line 10 and 11
The socket is created using the socket function. A socket is like a file handle-it can be read from, written to or both. The function setsockopt is called to ensure that the port will be immediately reusable.
Line 13
The sockaddr_in function obtains a port on the server. The argument INADDR_ANY chooses one of the server’s virtual IP addresses. You could instead decide to bind only one of the virtual IP addresses by replacing INADDR_ANY with inet_aton(“192.168.1.1″) or gethostbyname (‘localhost’)
Line 15
The bind function binds the socket to the port, i.e., plugs the socket into that port.
Line 16
The listen function causes the server to begin listening at the port. The second argument to the listen function is the maximum queue length or the maximum number of pending client connections. The value SOMAXCONN is the maximum queue length for the machine being used.
Line 20
Once the server begins listening at the port, it can accept client connections using the accept function. When the client is accepted, a new socket is created named CLIENT which can be used like a file handle. Reading from the socket reads the client’s output and printing to the socket sends data to the client. The return value of the accept function is the Internet address of the client in a packed format.
Line 24 and 25
The function sockaddr_in takes the packed format and returns the client’s port number and the client’s numeric Internet address in a packed format. The packed numeric Internet address can be converted to a text string representing the numeric IP using inet_ntoa (numeric to ASCII). To convert the packed numeric address to a host name, the function gethostbyaddr is used.
Start the script on a localhost. I ran these scripts on a Windows 2000 machine with Active PERL ( binary build 631 PERL v5.6.1). The output looks something like this.
D:GalantPerl>start server1.pl
SERVER started on port 7890
The server is now listening at port 7890 on the local host, waiting for clients to connect.
A Simple Client
1. #! /usr/bin/perl -w
2. # client1.pl – a simple client
3. #—————-
4. use strict;
5. use Socket;
6. # initialize host and port
7. my $host = shift || ‘localhost’;
8. my $port = shift || 7890;
9. my $proto = getprotobyname(‘tcp’);
10. # get the port address
11. my $iaddr = inet_aton($host);
12. my $paddr = sockaddr_in($port, $iaddr);
13. # create the socket, connect to the port
14. socket(SOCKET, PF_INET, SOCK_STREAM, $proto)
a. or die “socket: $!”;
15. connect(SOCKET, $paddr) or die “connect: $!”;
16. my $line;
17. while ($line = )
18. {
19. print $line;
20. }
21. close SOCKET or die “close: $!”;
Analysis
Line 7 and 8
Takes the command-line arguments of host name and port number or if no arguments are passed initializes variables with the default values.
Line 11 and 12
The host name and the port number are used to generate the port address using inet_aton (ASCII to numeric) and sockaddr_in.
Line 14 and 15
A socket is created using socket and the client connects the socket to the port address using connect.
Line 17 and 21
The while loop then reads the data the server sends to the client until the end-of-file is reached, printing this input to STDOUT. Then the socket is closed.
Output on the server:
D:GalantPerl>start server1.pl
SERVER started on port 7890
got a connection from: SHILPA[172.16.0.160]
Output on the client:
C:>\rahulperlclient1.pl rahul
Smile from the server
Socket Programming in PERL – PERL Makes Life Easy
Those scripts were a lot of PERL code just to send a few bytes of information across. It is possible to write some cute and short socket programs by using OO Concepts and the IO::Socket module. We shall see now, how it is possible.
Sample Script Server Using IO
1. #!/usr/bin/perl -w
2. # serIO.pl
3. # server using IO::Socket
4. #———————
5. use strict;
6. use IO::Socket;
7. my $sock = new IO::Socket::INET(
LocalHost => ‘localhost’,
LocalPort => 7890,
Proto => ‘tcp’,
Listen => SOMAXCONN,
Reuse => 1);
8. $sock or die “no socket :$!”;
9. my($new_sock, $c_addr, $buf);
10. while (($new_sock, $c_addr) = $sock->accept())
11. {
my ($client_port, $c_ip) =sockaddr_in($c_addr);
my $client_ipnum = inet_ntoa($c_ip);
my $client_host =gethostbyaddr($c_ip, AF_INET);
print “got a connection from: $client_host”,” [$client_ipnum] “;
while (defined ($buf = <$new_sock>))
{
print $buf;
}
12. }
Analysis
Line 7
A new IO::Socket::INET object is created using the new method The new method returns a socket that is assigned to $sock
Line 10
A client connection is accepted using the accept method. The accept method returns the client socket when evaluated in scalar context and the client’s socket and IP address when evaluated in list context.
Sample Client Script Using IO
1. #!/usr/bin/perl -w
2. # cliIO.pl
3. # a simple client using IO:Socket
4. #—————-
5. use strict;
6. use IO::Socket;
7. my $host = shift || ‘localhost’;
8. my $port = shift || 7890;
9. my $sock = new IO::Socket::INET( PeerAddr => $host, PeerPort => $port, Proto => ‘tcp’);
10. $sock or die “no socket :$!”;
11. foreach my $i (1..10)
12. {
13. print $sock “$i”,scalar(localtime),” “;
14. sleep(1);
15. }
16. close $sock;
Analysis
A new object is created which connects to the server and sends 10 timestamp strings with 1 second delay in between.
Output of the new cute scripts:
D:GalantPerl>start perl serIO.pl
D:GalantPerl>cliIO.pl
On the server window:
got a connection from: RAHUL [127.0.0.1]
1Thu Feb 6 12:52:57 2003
2Thu Feb 6 12:52:58 2003
3Thu Feb 6 12:52:59 2003
4Thu Feb 6 12:53:00 2003
5Thu Feb 6 12:53:01 2003
6Thu Feb 6 12:53:02 2003
7Thu Feb 6 12:53:03 2003
8Thu Feb 6 12:53:04 2003
9Thu Feb 6 12:53:05 2003
10Thu Feb 6 12:53:06 2003
Pinging in PERL
Perl makes life easy, with it various modules available. Let’s demonstrate this by writing a short and quick ping program.
Sample Ping Program
1. #!/usr/bin/perl
2. # ping.pl
3. # a simple ping program
4. #—————
5. use Net::Ping;
6. $pinghost = shift||”gsmgprs”;
7. print “Pinging $pinghost “;
8. $p = Net::Ping->new(“icmp”, 2);
9. for (;;) # infinite loop
10. {
11. unless ($p->ping($pinghost))
12. {
13. print “Fail: “, scalar(localtime), ” “;
14. } else
15. {
16. print “Success: “, scalar(localtime), ” “;
17. }
18. sleep 10;
19. }
Analysis
The Net::Ping makes pinging remote hosts easy and quick. An object of the class created. Here we use the icmp protocol (you can also choose tcp or udp).
A sample output:
D:GalantPerl>ping.pl
Pinging gsmgprs
Success: Thu Feb 6 14:22:01 2003
Success: Thu Feb 6 14:22:11 2003
Success: Thu Feb 6 14:22:21 2003
Success: Thu Feb 6 14:22:31 2003
Success: Thu Feb 6 14:22:41 2003
Success: Thu Feb 6 14:22:51 2003
Success: Thu Feb 6 14:23:01 2003
Success: Thu Feb 6 14:23:11 2003
Success: Thu Feb 6 14:23:21 2003
Success: Thu Feb 6 14:23:31 2003
Socket Programming in PERL – Conclusion
Perl is a powerful, easy to learn, widely accepted and supported language. The freely available modules on CPAN (including the modules for network programming) cater to all development needs.
Socket Programming Using PHP
Introduction to Sockets
This tutorial aims to raise your skills and clear up any confusion or questions you have regarding socket programming with PHP. Let’s first talk about what a socket is. Take a look at the picture below…it’s a normal to think of these when you hear the work “sockets”. Conceptually we can use these socket tools to get a clearer picture of just what sockets do. A socket is a plug or a way to connect to another computer. This computer might be in the next room or across the world which is known as network programming. Your computer is assigned an IP address. This IP address let’s any computer in the world know where to reach you (Let’s pretend for a minute that firewalls don’t exist and you’re connected directly to the internet) Computers communicate with your computer through “PORTS”. This allows around 65,000+ different applications to be talking to the internet at any given time. If you didn’t have ports, computers would have a hard time trying to find out what data was meant for what program.
The most common example of how to think about ports is the web. Normal web traffic goes over port 80. When you make a request for a webpage, your browser opens up a socket connection to port 80 on the machine you wish to view the webpage on and says “hey give me this page I want”. The web server on the other end is listening on port 80 for any requests. When it receives a request, it awaits for your command which typically says “GET /index.html HTTP/1.0\r\n” which tells the web server, “I want the index.html page on this website, jack!”. Another example is FTP which listens on port 21. So there are many applications out there that use these “ports” in your computer to communicate to the outside world. In fact this is how alot of the virus and trojans work. They keep a socket or port on your computer open to the outside world, waiting for commands to attack other computers or to send your personal details to a master computer. Clever eh? You can see a list of all your open socket connections by typing in “netstat” on any command line. This command lists all the computers currently connected to you and which ports they’re communicating on.
Sockets and PHP
PHP makes socket programming pretty easy. You can do alot of very complex tasks using sockets and PHP. One such task I have recently run into is writing a socket server that allows multiple applications to connect to it. All of these applications want to send their own little bits of information to parts of a system only I know about. They just want to send data to all administrators for example, however only I know where administrators are logged in at. Their c++ applications need to open up a socket to me, and send me the information that want to forward and I’ll do the job of finding out where those people are. PHP performs very well for this task.
So what’s involved in socket programming with PHP? Well let’s start off with a socket server. Its a very simple concept. You create a program that runs all the time, constantly running that just sits there and says “CONNECT TO ME!!! HERE I AM, OVER HERE ON PORT 10000″. Creating a socket server is very much like using a telephone. There are certain steps you have to do to make a telephone call right? Well there are certain steps to make a phone call to another computer as well. They look like so…
Install a Phone – socket_create()
Plug in the phone to the phone jack – socket_bind()
Turn the power to the phone on – socket_listen()
When the phone rings, you pick it up and talk! – socket_accept()
TCP & UDP Protocols
The majority of the time you’ll being using either TCP or UDP sockets. What’s the difference you may ask? TCP is a stateful connection protocol which means I know that if I send you the data “1,2,3″ that you’ll receive “1,2,3″. It’s much like a telephone conversation. When I pick up the phone I hear you on the other end, I can listen to what you tell me, I can talk back and I KNOW WHEN YOU HANG UP. That is important as UDP sockets do not follow that concept. A UDP socket is much like leaving someone a voicemail. You made the call, you told them your message but you have no idea if they’ll ever listen to your message.
The world wide web is built on TCP. You want to make sure you’re getting all of the web page displayed, not some of it. There are definitely uses for UDP as well. Music streaming is the most common example. If someone is sending you millions of packets of information while a song is playing, if something happens and some packets of data are lost, do you really want to hear the beginning of Stairway to Heaven(RIAA please don’t sue me for using a real song title you pricks) at the end of the song? Probably not, you just want to keep on listening.
PHP Socket Server
Let’s take a look at these steps one by one and see how the PHP commands and options affect our server. Our first goal is to create a socket server that will listen on Port 10000, accept a connection and then respond with a message from the server. We’ll start simple and get more complex as we go along.
Step 1
Looking at step one we see “Install a Phone – socket_create()”. What this does is creates a resource on the operating system for us to use. A socket descriptor. It’s exactly like when you use $fp = fopen(“myfile.txt”, “r”);. $fp now contains a “resource” that you must pass to other functions that want to operate on that file. It’s the operating systems way of saying, “here is a safe handle you can use to work with this thing”. Let’s take a look at the socket_create function itself. This is the function that acts like installing a phone in your house.
socket_create()
resource socket_create ( int domain, int type, int protocol )
When we make a call to socket_create() we are passing in 3 required parameters as you can see above. A typical call to socket_create() will look like this:
$mysock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
Let’s examine this function call. The first parameter you see is AF_INET. AF = Address Family and INET basically means Internet. So it’s the internet’s address family. 99.9% of the time this is the parameter you’ll want to use. This allows you to use UDP or TCP connections to communicate with computers. You could also use the option AF_UNIX, which means the Unix Address Family which would allow you to talk to processes running inside the unix system. So once again, just memorize AF_INET and you should be all set
The 2nd parameter you see there is “SOCK_STREAM”. SOCK_STREAM is a constant that tells the socket_create function to use a TCP connection. If you were to be using UDP sockets you would put SOCK_DGRAM as the parameter. You could also use SOCK_RAW if you wanted to craft your own layer of transport. Alot of gaming companies do this to get the speed of UDP but at least some acknowledgement that the msg arrives like TCP, so it’s sort of a TCP/UDP hybrid. That is not for the faint of heart however so we’ll stick with TCP for this example.
The 3rd parameter is SOL_TCP which says just use Socket Layer TCP pretty please.
Step 2
If you remembered the steps above you’d see we now have to “Plug in the phone to the phone jack – socket_bind()”. This effectively takes the socket resource that socket_create gives us and locks it into a specified port. So we first said “hey operating system, give me a cable I can use to get to the network”. The operating system, said “sure, here ya go” if everything went error free and then we tell it “ok operating system, here is that cable you gave me, why don’t you go plug it over there on port 10000 so I can start talking to people!”. So now with the socket_bind call we’re actually telling the OS to marry our application with the port number we tell it. Basically “hey Jack, anything that wants to talk over port 10000 wants to talk to me, so just send me the data.”.
socket_bind($mysock, “127.0.0.1″, 10000));
The first parameter is the resource variable that we received when we created our socket which is $mysock. This holds a resource to that bound socket so the OS knows which connection we’re passing around to all these functions. The 2nd parameter is the IP address we wish to bind to. In this case it’s our local IP address 127.0.0.1. The final parameter is the port which is 10000. Now our socket is “plugged in” to the operating system.
Step 3
So we created our socket, bound it to the operating system on port 10000 and now all we have to do is power it up and get ready to start listening for someone to call us! “Turn the power to the phone on – socket_listen()”. What this function does is basically tell the Operating System you’ve done the grunt work of setting up your socket and now you’re all ready to start getting phone calls. It also let’s you define how big your waiting cue is. The 2nd parameter to socket_listen is the “backlog” or how many connections should we queue up while we’re waiting to deal with another connection. It’s very much like calling a busy company’s main telephone number. If you call while they’re trying to help someone else the receptionist will pick you up and say “please hold”. They’ll put you in the holding cue and you’ll be a little flashing light on her phone board. If too many people call and there’s no more hold spots to fill, you can’t get through to that company anymore. Much like a socket will start dropping incoming connections if the cue is full. When she’s done with that guy, she picks you up and starts talking to you which frees up another holding spot.
socket_listen($mysock, 5);
You can see we again pass in the resource handler which is $mysock. We also pass in the number 5 which again means. “While I’m on the phone with someone, you can put up to 5 people on hold until I’m done servicing this one”.
Putting it all together
Let’s put some basic socket code together to create a very basic socket server. We won’t add error checking in this example. We’ll save that for the next task.
#!/usr/bin/php -q
<?php
$address = “10.139.17.143″;
$port = “10000″;
/* create a socket in the AF_INET family, using SOCK_STREAM for TCP connection */
$mysock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($mysock, $address, $port);
socket_listen($mysock, 5);
$client = socket_accept($mysock);
// Read the input from the client – 1024 bytes
$input = socket_read($client, 1024);
$output = “thanks for connecting, you wrote: “.$input.”\r\n”;
// Display output back to client
socket_write($client, $output);
socket_close($client);
socket_close($mysock);
?>
Let’s take a look at some new lines of code we added here. the first line is the “she bang” line telling the operating system where it can find our PHP executable. Since we aren’t going to use the webserver, we must tell it what will execute this script. Put in the path to where your php executable lives. We create our socket, bind it and listen as we previously discussed. Now we’re all ready to receive connections and we let the socket_accept function do that for us. So the call to $client = socket_accept($mysock); gives us the $client variable which is a resource to the currently connected user. socket_accept only takes one variable which is the new client connection so that one is easy. We can now start reading what this client is sending us, storing it in the $input variable. We pass in the $client’s resource variable along with 1024 which means “Read in the first 1024 bytes of their message”. We then take that input and output our own message letting the user know what they’ve typed. We close the sockets and the program exits. This server handles one client and then dies, not very useful but its the bare minimum of a socket server.
Now let’s start our socket server and make a connection to it. Open a command prompt and execute your server. If we saved this file as app_server.php we’ll chmod it to 777 to make it executable, then we’ll start it with ./app_server.php
It should now be hanging there waiting for a connection.
Now you should be albe to open up another command prompt and type in: telnet 127.0.0.1 10000
http://knowinphp.files.wordpress.com/2009/06/sockettelnet.jpg
Which means open up a session to my local machine on port 10000. You’re trying to connect to your socket server. If all goes well you can type in a message, hit enter, and the socket server will reply a message back to you.
http://knowinphp.files.wordpress.com/2009/06/sockettelnet1.jpg
This is by no means a socket server that should be used on a web site but again it is the bare minimum you can do to reply to a client. Next section we’ll start beefing this puppy up and making it into a more robust socket program.
40 Tips for optimizing your php code
- If a method can be static, declare it static. Speed improvement is by a factor of 4.
- echo is faster than print.
- Use echo’s multiple parameters instead of string concatenation.
- Set the maxvalue for your for-loops before and not in the loop.
- Unset your variables to free memory, especially large arrays.
- Avoid magic like __get, __set, __autoload
- require_once() is expensive
- Use full paths in includes and requires, less time spent on resolving the OS paths.
- If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
- See if you can use strncasecmp, strpbrk and stripos instead of regex
- str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
- If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
- It’s better to use switch statements than multi if, else if, statements.
- Error suppression with @ is very slow.
- Turn on apache’s mod_deflate
- Close your database connections when you’re done with them
- $row[’id’] is 7 times faster than $row[id]
- Error messages are expensive
- Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
- Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
- Incrementing a global variable is 2 times slow than a local var.
- Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
- Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
- Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
- Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
- Methods in derived classes run faster than ones defined in the base class.
- A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.
- Surrounding your string by ‘ instead of ” will make things interpret a little faster since php looks for variables inside “…” but not inside ‘…’. Of course you can only do this when you don’t need to have variables in the string.
- When echoing strings it’s faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
- A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
- Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.
- Cache as much as possible. Use memcached – memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request
- When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function. This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.
Ex.
if (strlen($foo) < 5) { echo “Foo is too short”; }
vs.
if (!isset($foo{5})) { echo “Foo is too short”; }
Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it’s execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string’s length.
- When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don’t go modifying your C or Java code thinking it’ll suddenly become faster, it won’t. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend’s PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
- Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
- Do not implement every data structure as a class, arrays are useful, too
- Don’t split methods too much, think, which code you will really re-use
- You can always split the code of a method later, when needed
- Make use of the countless predefined functions
- If you have very time consuming functions in your code, consider writing them as C extensions
- Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview
- mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%
Using PHP IMAP functions to download email
This post looks at how to connect to a POP or IMAP mailbox using PHP’s IMAP mail functions and retrive the number of messages in the mailbox, the message headers and body, and then to delete the message.
IMAP functions not installed?
If you get the error message “Fatal error: Call to undefined function imap_open()” when trying to connect to the mailbox then the IMAP functions are not installed in your PHP install. I detailed how to install this in an earlier post today for CentOS. Other Linux distibutions will have similar methods for installing the IMAP extension.
Connecting to the mailbox
To connect to a POP3 mail server, do the following, where $server contains the server to connect to, $login and $password the login name and password used to access the mailbox:
$connection = imap_open(‘{$server:110/pop3}’, $login, $password);
If it’s an IMAP server you can leave out the port number and slash part:
$connection = imap_open(‘{$server}’, $login, $password);
The value returned will either be an IMAP resource or boolean false in the event of an error.
Note that if you’re getting “Warning: imap_open(): Couldn’t open stream” type of errors when connecting you may need to append the /notls flag after the server e.g.:
$connection = imap_open(‘{$server}/notls’, $login, $password);
I found that I needed to do this when moving a script from CentOS with PHP 5.1.6 to Debian with PHP 5.2.6. On Debian it would give the error unless I had the “notls” flag. Obviously if you need tls or ssl then you’d add those flags instead of notls.
Get the number of messages
To get the number of messages in the mailbox use the imap_num_msg() function like so:
$count = imap_num_msg($connection);
Loop through and retrieve the messages
Use a simple loop to loop through from 1 to the number of messages combined with the imap_headerinfo and imap_body functions to get the message headers formatted into an object and the raw body respectively.
for($i = 1; $i <= $count; $i++) {
$header = imap_headerinfo($connection, $i);
$raw_body = imap_body($connection, $i);
}
Note that the imap_body() function returns the raw body of the email messages, which also contains all the mime parts and attachments etc (if present), not just the plain text message. I will deal with looking at the parts of an email message in next Monday’s PHP post.
Header object
The value returned from the imap_headerinfo() function is an object containing a number of properties. To show the values available, an example of the output from print_r is as follows:
stdClass Object
(
[date] => Wed, 4 Feb 2009 22:37:42 +1300
[Date] => Wed, 4 Feb 2009 22:37:42 +1300
[subject] => Fwd: another test
[Subject] => Fwd: another test
[in_reply_to] => <59f89e00902040137vb73ed1ep5f870dafe02f26cf@mail.example.com>
[message_id] => <59f89e00902040137s16c317b6oa4658a4d2cc64c3c@mail.example.com>
[references] => <59f89e00902040137vb73ed1ep5f870dafe02f26cf@mail.example.com>
[toaddress] => john@example.com
[to] => Array
(
[0] => stdClass Object
(
[mailbox] => john
[host] => example.com
)
)
[fromaddress] => Chris Hope
[from] => Array
(
[0] => stdClass Object
(
[personal] => Chris Hope
[mailbox] => chris
[host] => example.com
)
)
[reply_toaddress] => Chris Hope
[reply_to] => Array
(
[0] => stdClass Object
(
[personal] => Chris Hope
[mailbox] => chris
[host] => example.com
)
)
[senderaddress] => Chris Hope
[sender] => Array
(
[0] => stdClass Object
(
[personal] => Chris Hope
[mailbox] => chris
[host] => example.com
)
)
[Recent] => N
[Unseen] =>
[Flagged] =>
[Answered] =>
[Deleted] =>
[Draft] =>
[Msgno] => 20
[MailDate] => 4-Feb-2009 22:37:42 +1300
[Size] => 3111
[udate] => 1233740262
)
Extracting attachments from an email message using PHP IMAP functions
This post is part of an ongoing series which aims to show how to extract data from Google Analytics using its scheduled email reports system. I have already looked at how to send Google Analytics data by email, and how to use the PHP IMAP functions to download email. I will also look at using other PHP libraries to download email and attachments, but for now this post looks at how to extract email attachments using the PHP IMAP functions.
There are other was to do this – the method presented here is just one of several was of getting the attachments. I will look at other ways to get attachments from email messages in later posts.
Getting the message structure
After logging in to the IMAP or POP mail server (detailed in my last post in this series about how to use the PHP IMAP functions to download email) use the imap_fetchstructure() function to get the structure of the message.
The following code snippet example uses the connection stored in $connection to download the message structure for the $message_number message in the mailbox (this is a 1 based index of the messages in the mailbox):
$structure = imap_fetchstructure($connection, $message_number);
Assuming all went well we now have an object containing a lot of information about the message. The following is output from print_r for a message sent from Google Analytics containing tab-separated data in an attachment:
stdClass Object
(
[type] => 1
[encoding] => 0
[ifsubtype] => 1
[subtype] => MIXED
[ifdescription] => 0
[ifid] => 0
[ifdisposition] => 0
[ifdparameters] => 0
[ifparameters] => 1
[parameters] => Array
(
[0] => stdClass Object
(
[attribute] => boundary
[value] => 00221532c8aca27cf00462632bb7
)
)
[parts] => Array
(
[0] => stdClass Object
(
[type] => 0
[encoding] => 0
[ifsubtype] => 1
[subtype] => PLAIN
[ifdescription] => 0
[ifid] => 0
[lines] => 11
[bytes] => 737
[ifdisposition] => 0
[ifdparameters] => 0
[ifparameters] => 1
[parameters] => Array
(
[0] => stdClass Object
(
[attribute] => charset
[value] => ISO-8859-1
)
[1] => stdClass Object
(
[attribute] => format
[value] => flowed
)
[2] => stdClass Object
(
[attribute] => delsp
[value] => yes
)
)
)
[1] => stdClass Object
(
[type] => 0
[encoding] => 3
[ifsubtype] => 1
[subtype] => TAB-SEPARATED-VALUES
[ifdescription] => 0
[ifid] => 0
[lines] => 111
[bytes] => 8674
[ifdisposition] => 1
[disposition] => attachment
[ifdparameters] => 1
[dparameters] => Array
(
[0] => stdClass Object
(
[attribute] => filename
[value] => Analytics_www.electrictoolbox.com_20090108-20090207.tsv
)
)
[ifparameters] => 1
[parameters] => Array
(
[0] => stdClass Object
(
[attribute] => charset
[value] => US-ASCII
)
[1] => stdClass Object
(
[attribute] => name
[value] => Analytics_www.electrictoolbox.com_20090108-20090207.tsv
)
)
)
)
)
Working out and getting the attachments
The above isn’t the easiest to extract the information we need. You can see we need to loop through [parts] and then each part’s [parameters] and [dparameters] to get the filename and name for each, downloading the message part using imap_fetchbody() if it is. If the part doesn’t have a name then it’s not an attachment.
This is achieved with the following code, assigning information to a array called $attachments. The reason 1 is added to $i in the call to imap_fetchbody() is that the parts are zero-based but in the IMAP functions they are one-based.
$attachments = array();
if(isset($structure->parts) && count($structure->parts)) {
for($i = 0; $i < count($structure->parts); $i++) {
$attachments[$i] = array(
‘is_attachment’ => false,
‘filename’ => ”,
‘name’ => ”,
‘attachment’ => ”
);
if($structure->parts[$i]->ifdparameters) {
foreach($structure->parts[$i]->dparameters as $object) {
if(strtolower($object->attribute) == ‘filename’) {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters) {
foreach($structure->parts[$i]->parameters as $object) {
if(strtolower($object->attribute) == ‘name’) {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($connection, $message_number, $i+1);
if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
The end result of the above code on our example email is the following, with the data truncated for the actual attachment:
Array
(
[0] => Array
(
[is_attachment] =>
[filename] =>
[name] =>
[attachment] =>
)
[1] => Array
(
[is_attachment] => 1
[filename] => Analytics_www.electrictoolbox.com_20090108-20090207.tsv
[name] => Analytics_www.electrictoolbox.com_20090108-20090207.tsv
[attachment] => …
)
)
You can now loop through the $attachments array looking for the appropriate filename to do whatever processing you need to it.