Sunday, April 12, 2009

The nature of the HTTP protocol

When first learning web programming and web design, a very basic thing it is good to understand from the very beginning is the nature of the HTTP protocol. That's because everything you are going to do will be based on this protocol. HTTP is a "connect-and-disconnect" type of protocol. Here's a hopeful diagram (which I will explain shortly): I will try my best to explain this simple yet very important diagram. Let's say you have this PHP file named hello.php, in the root of your web server: <?php echo "Hello, World!"; ?> Here's what happens when you enter http://localhost/hello.php in your browser (which I will call the client from now on):
  1. The client connects to the web server and tells it it wants the hello.php file;
  2. The server realizes the file is a PHP file, so it runs it through the PHP parser;
  3. The PHP parser parses the hello.php file and returns the output to the web server;
  4. The web server takes the output from the PHP parser which, in our case, will be the simple string Hello, World! and passes it back to the client.
This is essential in web development because you have to have the difference between client side and server side languages as clear as possible in your mind. If you don't, you will find yourself making basic mistakes such as trying to call a PHP function from Javascript, for example: <script type="text/javascript"> function someFunc(someArg) { alert("<?php echo somePhpFunc($someArg); ?>"); } </script> The above code will fail horribly because all the PHP code is executed before the script is sent to the client. Basically, the somePhpFunc function will be called only once, with an empty argument and will probably return an empty string (because it doesn't expect an empty argument). Thus, the script will reach the client in this form: <script type="text/javascript"> function someFunc(someArg) { alert(""); } </script> which is definitely not what you want. Tip: When in doubt, always look at the source code of the web page through your browser (usually View -> Page Source) to see what is actually being sent to the client. Note: I have used PHP for my examples because it's the easiest language to give examples in and almost everyone knows a little bit of it. If not, you can easily figure out what echo "Hello, World!"; does. What I have said here applies to all server side languages, such as Python, Perl, Java, Coldfusion, ASP (bleh), byte code etc. I hope I helped somebody :-)

No comments:

Post a Comment