Making cross-sub-domain ajax (XHR) requests using mod_proxy and iframes

One of the restrictions imposed by all browser side programming languages is that one cannot make cross-domain ajax requests. This restriction comes because of the same origin policy and even sub-domain ajax calls are not allowed. In this blog post, I will demo two methods of making cross-sub-domain ajax requests. First demo will use mod_proxy module of Apache. While the second demo will use iframe and javascript tricks for making sub-domain ajax requests.

Using mod_proxy for cross-domain ajax requests
By enabling mod_proxy module of apache2, we can configure apache in reverse proxy mode. In reverse proxy mode, apache2 appears be like an ordinary web server to the browser. However depending upon the proxy rules defined, apache2 can make cross-domain request and serve data back to the browser.

Demo Link for Cross Domain Ajax using Apache mod_proxy

In this demo, I will make cross-domain request to http://gtalkbots.com/reverse-proxy-data.php. To make this cross-domain request successful, I have configured apache2 as shown below:

  1. Enable mod_proxy module.
    $ a2enmod proxy
    $ a2enmod proxy_http
    $ a2enmod proxy_connect
  2. Add the following lines to httpd.conf:
    $ cat /private/etc/apache2/httpd.conf | grep mod_proxy
    
    LoadModule proxy_module libexec/apache2/mod_proxy.so
    LoadModule proxy_connect_module libexec/apache2/mod_proxy_connect.so
    LoadModule proxy_http_module libexec/apache2/mod_proxy_http.so
  3. Create a file reverse-proxy.conf and add the following config:
    $ cat /private/etc/apache2/other/reverse-proxy.conf
    
    ProxyRequests Off
    
    <Proxy *>
    Order deny,allow
    Deny from all
    Allow from .abhinavsingh.com
    </Proxy>
    
    ProxyPass /webdemos/crossdomainajax/reverse-proxy-get.php http://gtalkbots.com/reverse-proxy-data.php
    ProxyPassReverse /webdemos/crossdomainajax/reverse-proxy-get.php http://gtalkbots.com/reverse-proxy-data.php

In brief, when Apache sees an incoming ajax request to /webdemos/crossdomainajax/reverse-proxy-get.php , it simply proxy pass it to http://gtalkbots.com/reverse-proxy-data.php and return back the response. The whole process is hidden from the users on the demo page.

Using iframes for cross-domain ajax requests
Another method of achieving sub-domain ajax requests is by using iframes. However, javascript does not allow communication between two frames if they don’t have same document.domain. The simplest of the hacks to make this communication possible is to set document.domain of the iframe same as that of the parent frame.

Demo Link for Sub-Domain Ajax using iFrames

In this demo, I will make a sub-domain request to http://img1.abhinavsingh.com/iframe-data.php. To make this possible, I load an iframe with src="http://img1.abhinavsingh.com/iframe-demo.php" and set document.domain="abhinavsingh.com"; for the iframe.

iframe-demo.php

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
	jQuery(function($) {
		function getTimestamp() {
			$.get(ajax_url,
				{},
				function(data) {
					$('#iframe_ajax_data', top.document).html('Server time received through iframe ajax: '+data);
				}
			);
		}

		document.domain = "abhinavsingh.com";
		$('#link', top.document).click(function() {
			getTimestamp();
		});
	});
</script>

In brief, iframe-demo.php sets an onclick event on $('#link' top.document) , which makes a sub-domain ajax request to http://img1.abhinavsingh.com/iframe-data.php

Enjoy!

How does PHP echo’s a “Hello World”? – Behind the scene

Have you ever wondered how PHP echo’s a “Hello World” for you on the browser? Even I didn’t until I read about the PHP internals and extensions. I thought may be a few out there will be interested in exploring the other side of PHP, so here we go.

In my last post I discussed in brief “How your browser reaches to my server when you type http://abhinavsingh.com in address bar?”. Read through if you have missed out on that. Here I will discuss in brief “How does PHP churns out the content requested on the webpage?”

An Overview
Here is what happens step-wise:

  1. We never start any PHP daemon or anything by ourself. When we start Apache, it starts the PHP interpreter along itself
  2. PHP is linked to Apache (In general term SAPI i.e. a Server API) using mod_php5.so module
  3. PHP as a whole consists of 3 modules (Core PHP, Zend Engine and Extension Layer)
  4. Core PHP is the module which handles the requests, file streams, error handling and other such operations
  5. Zend Engine(ZE) is the one which converts human readable code into machine understandable tokens/op-codes. Then it executes this generate code into a Virtual Machine.
  6. Extensions are a bunch of functions, classes, streams made available to the PHP scripts, which can be used to perform certain tasks. For example, we need mysql extension to connect to MySQL database using PHP.
  7. While Zend Engine executes the generated code, the script might require access to a few extensions. Then ZE passes the control to the extension module/layer which transfer back the control to ZE after completion of tasks.
  8. Finally Zend Engine returns back the result to PHP Core, which gives that to SAPI layer, and finally which displays it on your browser.

A Step Deeper
But wait! This is still not over yet. Above was just a high level flow diagram. Lets dig a step deeper and see what more is happening behind the scenes:

  1. When we start Apache, it also starts PHP interpreter along itself
  2. PHP startup happens in 2 steps
  3. 1st step is to perform initial setup of structures and values that persists for the life of SAPI
  4. 2nd step is for transient settings that only last for a single page request

Step 1 of PHP Startup
Confused over what’s step 1 and 2 ? No worries, next we will discuss the same in a bit more detail. Lets first see step 1, which is basically the main stuff.
Remember step 1 happens even before any page request is being made.

  1. As we start Apache, it starts PHP interpreter
  2. PHP calls MINIT method of each extension, which is being enabled. View your php.ini file to see the modules which are being enabled by default
  3. MINIT refers to Module Initialization. Each Module Initialization method initializes and define a set of functions, classes which will be used by future page requests

A typical MINIT method looks like:

      PHP_MINIT_FUNCTION(extension_name) {

          /* Initialize functions, classes etc */

      }

Step 2 of PHP Startup

  1. When a page request is being made, SAPI layer gives control to PHP layer. PHP then set up an environment to execute the PHP page requested. In turn it also create a symbol table which will store various variables being used while executing this page.
  2. PHP then calls the RINIT method of each module. RINIT refers to Request Initialization Module. Classic example of RINIT module implementation is the Session’s module. If enabled in php.ini, the RINIT method of Sessions module will pre-populate the $_SESSION variable and save in the symbol table.
  3. RINIT method can be thought as an auto_prepend_file directive, which is pre-appended to every PHP script before execution.

A typical RINIT method looks like:

      PHP_RINIT_FUNCTION(extension_name) {

          /* Initialize session variables, pre-populate variables, redefine global variables etc */

      }

Step 1 of PHP Shutdown
Just like PHP startup, shutdown also happens in 2 steps.

  1. After the page execution is complete either by reaching the end of the script or by call of any exit() or die() function, PHP starts the cleanup process. In turn it calls RSHUTDOWN method of every extension. RSHUTDOWN can be thought as auto_append_file directive to every PHP script, which no matter what happens, is always executed.
  2. RSHUTDOWN method, destroys the symbols table (memory management) by calling unset() on all variables in the symbols table

A typical RSHUTDOWN method looks like:

      PHP_RSHUTDOWN_FUNCTION(extension_name) {

          /* Do memory management, unset all variables used in the last PHP call etc */

      }

Step 2 of PHP Shutdown
Finally when all requests has been made and SAPI is ready to shutdown, PHP call its 2nd step of shutdown process.

  1. PHP calls the MSHUTDOWN method of every extension, which is basically the last chance for every extension to unregister handlers and free any persistent memory allocated during the MINIT cycle.

A typical RSHUTDOWN method looks like:

      PHP_MSHUTDOWN_FUNCTION(extension_name) {

          /* Free handlers and persistent memory etc */

      }

And that brings us to the end of what we can call as PHP Lifecycle. Important point to note is that Step 1 of Startup and Step 2 of Shutdown happens when no request is being made to the web servers.

I hope this post will clear many doubts and un-answered questions which you might have.

Do leave a comment and feedbacks.

How to make faster websites and enhance your site user experience – Part 1

In all my posts till now I concentrated over how to get started with web development and related introductory stuffs. In next few posts (series of 3 posts), I will write some of my learning in the field of “How to make your website faster and enhance your site user experience”.

So lets assume I made a site, which rocks with all those web2.0 features in it. But still my user complaints like:

  1. My site hangs their browser while loading.
  2. The page takes too long to load.
  3. Blah Blah Blah…… 🙁

So how to go about and make sure that you do your best to make things rocking. Here are a few of my tips on things that you should concentrate upon and which will definitely help in fast loading of your pages:

  1. GZip your site static content: This is one of the most important stuff which helps a great deal in enhancing your site download speed. Let me explain the process:
    • When I type www.yahoo.com in my browser and press enter, an interaction starts between my browser and the www.yahoo.com servers. My browser asks for the yahoo.com homepage from the yahoo servers. However all Grade-A browsers sends a few useful stuff along with this homepage request. They tells the server that I support gzip encoding, and if you serve me the contents in g-zipped format I will happily except it, unzip at my end and render it for the user.
    • The Yahoo server sees these headers being sent by the browser and depending upon its configuration it gzips the content before serving back to the browser. However, if Yahoo server’s are not configured for the gzip encoding, it will server the content in its raw form. Further, if Yahoo server’s are configured for gzip encoding but my browser isn’t a Grade-A browser, servers are smart enough to return back the content in the form which suits my browser.
    • For instance here are the request header sent by my browser to the yahoo servers when I type in http://yahoo.com in my browser:

      In the above image we can very well see that my browser sends in a header saying Accept-Encoding : gzip,deflate. On seeing this in the headers Yahoo server responds as expected i.e. it serves back the gzipped contents to the browser.

      In the above image we see the response headers being sent by the Yahoo server to my browser. We can see that Yahoo server tells back my browser that it has served the contents in Content-Encoding : gzip , so please unzip them at your end before rendering them for the user.

      So how does the end user’s experience gets enhanced?

      If we see the above image we can very well see that the Yahoo homepage which is actually of 125.1Kb comes in as 31.9Kb only. Further the javascript files gets compressed and hence faster data transfer through the channels and thus faster experience for your site users.

      Though gzipping the site content increases your server side CPU load, but that gets compensated by the fast that users are able to see your pages load faster.

    • What all contents should I gzip? Its always better to gzip the javascript files, CSS files, HTML files, Plain Text files (In some cases XML’s too but I have had a few problems with gzipped XML’s). We generally don’t compress images, pdf’s etc as they are already in best compressed format and further compressing won’t give us any smaller file sizes.
  2. Setting an ETag for your sites content: This is another factor which helps the page load faster for the users. By setting up an ETag , server sends an information about the contents being served to the browser, telling the browser about its last modified date. So when I type in http://yahoo.com in my browser and presses enter, my browser requests for content from the Yahoo servers. In reply if it sees that the ETags haven’t changed for the requested component, it simply uses the component from browser’s cache. Hence this time we saves the data transfer part, as browser is capable enough to cache enough static data from one single domain.

    In the above image Yahoo servers doesn’t reply back the ETags possibly because of two reasons. Advertisements and Expires Headers which we will see in the next point. As Yahoo have advertisements on all their pages, they simply don’t want those contents to be cached by our browsers. So that everytime we open yahoo.com , we see a new advertisement. (Experts, Kindly correct me if I am wrong in my explanation here)

  3. Setting up the Expires headers: This factor even saves the browser pinging the server time.

    In the above image we can see Yahoo servers setting up an expire header telling the browser that, this component is not going to change before the setup expired header. Hence next time you type in Yahoo.com in your browser and press enter, browser sees the content which still haven’t expired and picks them up from the browser cache. Thus they don’t even ping the servers, saving your servers BW and enhancing your users page load time.

    What if I have setup expired headers 2 months from today and I want to change the content before that?
    Simple enough, next time in place of http://l.yimg.com/us.js.yimg.com/lib/bc/bc_2.0.4.js will be change to something like http://l.yimg.com/us.js.yimg.com/lib/bc/bc_2.0.5.js ,  i.e. changing the version of the javascript file being served from server side. Hence browser will be forced to download the new javascript file from the servers rather than using them from the cache.

  4. Use of sub-domain or different domain for serving static contents: We can very well see in the above image that Yahoo serves all its javascript files from a server called http://l.yimg.com which is supposedly one of its static server. But why the hell do I need to do this? This is because currently all Grade-A browsers allows 2 parallel connections to a host. i.e while loading a page yahoo.com, my browser can download only two files at a time from the yahoo yahoo.com server. Hence this will make other contents to go in queue, wait for the already downloading contents to finish before they get downloaded.

    Hence for the same reasons, we generally server our static content from one or more different sub0domains or full-domains all together. In future Internet Explorer 8 and Firefox are planning to increase this 2 requests per domain to 4-8 requests per domain.

  5. Minify your Javascripts and CSS files: What is minify? It was something developed and introduced by Douglas Crockford. Minifying your sites javascripts and CSS files two purpose at the same time. They decreases the size of your javascripts and CSS files and also hides (make it tougher to parse by others) your javascript calls. I minified javascript file will look like this:

    We can see it makes the size of javascript file by eliminating unwanted white spaces and blank lines. Plus it also makes it difficult for a hacker to tweak in the javascript file.

  6. Put CSS on top and JS at the bottom , avoid inline javascripts: By putting CSS on top ensures that user’s browser will render the page content for your users as and when it gets the HTML content. We want to put Javascripts at the bottom and avoind inline scripts, because while the page loads we do not want browser to start executing the contents in javascripts, which may create a lock time for other contents before they gets downloaded.

Thats it! There are a lot of other things which you may want to do, for making your site page load faster. But the above described 6 points dominates the page load time. I am no expert and still learning the tid-bits of scalable websites, hence if you find any mis-leading content , kindly leave a comment. I will be more than happy to edit the post.

PS: These are a few of the frontend things that we can do on the frontend to make our sites faster. In my next post of this series I will try to bring in the key backend things which can help in faster loading of the webpages.

Enjoy making cooler, faster webpages for your users 🙂

How to get started with web development?

Many of my friends have asked me on how to start with web development. I am not expert but here in this post I would like to describe a few steps that might help one climb the ladder of web development fast. Kindly feel free to add to this blog post if you think some other methodology might be better off.

  1. Where do I start web development? Well the first and best place to start web development is your own system. Yes your very own personal computer. You don’t need a server on internet to start with. Infact I worked locally on my computer for about a month before I went for free hostings, shared hosting and finally VPS. Once you feel that you are comfortable enough with the tid-bits of web development, then you can move to one of them.
  2. How to configure my local computer for that? You have a number of options to start with. I personally started on Tomcat Server after my initial training at Oracle. Tomcat is suited if you are starting with JSP (Java Server/Servlet Pages) . I started by making a few basic pages like creating a login/registration system. I made a few and then hosted on my office computer. Distributed the links to a few around to get the much needed boost. (Yes if you are into web development you need a lot of encouragement and appreciation from others, else your enthusiasm can soon die out). However I soon realized that in todays world of web 2.0 Tomcat is not the thing. So I shifted to Apache.

    Next option you have is to go for Apache (which I use currently for all my developments). I have written 2 posts on how to configure your local system for the same. Read it here: Web Development Part 1 Apache MySQL PHP . If you are interested in starting on a unix machine (which is always the best thing to do) here is the post where I described: How to configure Ubuntu and LAMP on Windows.

  3. Things to concentrate upon initially? Before you go for any big big applications its better to get your basics right. I sucked for long while working with out dated styles and methodology. Here is a bunch of things which you should initially look to:
    • Choose the <div> style to create your HTML pages. I didn’t knew about this methodology and even went ahead to release Altertunes with <table> structure HTML pages.
    • While looking around on internet you will find loads and lot of framework offerings. They really make your work sooo simple. Takes all the burden away from you. Solves all cross browser compatibility for your application and what not. Find a list of frameworks I have tried before here: Essential Frameworks for web development
    • However one thing which you lose by using such frameworks is the insight. You never get to know what cross browser compatibility issues comes and how are they solved. They provide you easy ajax requests but you never get to know the methodology behind it. The biggest drawback which I find is that even for a simplest of application you always need to include whole bunch of files from framework hence making your application heavy for no reason.
    • Hence I finally went ahead coding everything from scratch and never ever used any framework for any of my works.
    • You need to learn how to prevent XSS (Cross browser scripting) and SQL Injection in your applications. Something very important for all your applications.

  4. Getting to a free hosting server: After initial play at your PC, its time to get to a free hosting server which brings in more knowledge and experience. I am lucky in the fact that I moved to X10 Hosting for the very first time. In my opinion they are one of the best in providing free hosts. The amount of features and largely the amount of support at their forums make them the best free hosting services around. I started with http://imoracle.x10hosting.com as my first ever site. Few applications which I build on that were:
    • User login and registration system, where user was authenticated by an link sent to him through email.
    • Inside I had a few basic applications including contact form, multiple picture uploads etc etc.
    • One of the finest feature I had in that was Gmail Contact Import script, which I made using PHP Curl application.
    • Last but not the least I built a chat application similar to browser based chat applications in google and yahoo mails. (Though not that efficient). That was first and the last time I used a framework for any of my application. It was built using Prototype Windows Class framework.

    I told you about these features as these were the applications which got me started initially. Helped me learn the tid bits of web development. May be you too can give a try to a few of them as your first few applications.

  5. Altertunes: Must be wondering why is this name up here again. Well I agree Altertunes fails as a full time product on web but then actually this self initiated project helped me learn all and everything about web development. It was hugely an ajax dominated website with ajax requests flowing in and out of everything you do inside. Basically the social networking aspect inside altertunes helped me learn most of the things. Key things inside altertunes which helped me develop my web dev skills are:
    • Social networking aspects like adding friends, sending personal messages, dedicating a song to your friends etc etc.
    • Importing Gmail, Yahoo and other email contacts. I initially used self made gmail address book import script. But then probably Gmail changed the ways on their mail and my script started failing. However I was lucky to find various services which helps you import mail contacts.
    • Creating of search bots for mp3. This was one of the things done in PERL instead of PHP. Read my blog on how to create an html parser using PERL here. This search bot was similar to any other search bot but it only used to index mp3 files in the database.
    • Use of various web services API’s like Artist Recommendation API by last.fm, Video API by YouTube, Pictures API by Google.
    • Features like creating your custom playlists, bookmarking artists, creation of analytic backend engine to provide users with the best recommended songs based on users listen history.
    • Finally, I learnt to make custom web players. Alterplayer which I made using OpenLaszlo, was something which I did out of PHP, MySQL, Apache.
    • Being at Oracle at that point in time, helped me in maintaining such a relational database with ease.
    • Auto suggest feature which is similar to google auto suggest. Altertunes used to offer you artist names as you typed in the name of the artist.
    • News from Google and Yahoo news. As there were no API’s available for this, I scrapped the google and yahoo news using PERL scripts and showed them to the users. (Illegal it was though) 😉

    However I must say that your website is not complete till you have all the look and feel and User Interface to lure the users. Initially I thought that the UI is coming up good but then as the features which I wanted to offer increased and with my sucking <table> structured HTML pages everything got screwed. However Altertunes helped me develop my web dev skills a hell lot and helped me understanding the right way of doing things. Probably picking up a small project for yourself is always the best idea, as then only you will always try to make your application look more professional.

  6. Time for a shared host : As the traffic increased on Altertunes I had to quickly shift to a shared hosting. I again went for a shared hosting at X10, where I bought a hosting server for around 80$ a year with 99% uptime till date. All my websites including Altertunes, My personal website and a few other under ground works of mine are hosted on the same shared host. Basically shared host assures you of more % uptime, more bandwidth and more forum support from X10. Those guys just go out of their ways at times to help you out.

    However you always have few drawbacks of a shared host:

    • First of all its a shared host i.e. a single CPU with many document roots (one root for each client) in it. At times hosting service providers over shoot the maximum allowed roots on a single CPU, which makes your CPU share low. And hence sucking performances.
    • Your site can go down even without a single error from your side. Yes this is the case which happened with me, when one of the other user on the same CPU set up a cron job (an automated job which runs every X hours) to take a backup of his server every 1 hour. Well in that case every single hour he used to consume maximum CPU cycles and hence all other users their started experiencing major downtimes. However X10 forum moderators are kind enough. They take immediate actions in such cases and ensure everything is fine.
    • You can’t have all PHP PEAR and Perl modules installed. I wanted to have a PHP PERL module installed for me by which I can write perl codes inside my PHP script. But as its a shared host and a package installed effects everyone on the CPU, I was denied by the X10 hosting admins.
    • Similarly for creating a upload meter application you need to have APC (Alternate PHP Cache) module enabled on your server. And I was again denied this package by the X10 hosting as they will cache all other users file which they might not want to.
    • Finally the biggest drawback is that you don’t have access to the httpd.conf i.e you apache server configuration file and your php.ini your php configuration file. Which at times you may want to change to meet your applications demand.

  7. Finally time for a VPS (Virtual Private Server) : When you start feeling you want a total control on your server and applications, its time to switch to a VPS. However they will cost you more than expected. I started with VPS at VPSFarm which I must say totally sucks. Doesn’t go well for me atleast with Zero support (‘Zero’ means zero). I took the Xen 1024 plan which costs around 40$ per month. However by the time my 1st month got over X10 started offering VPS too and with my experience and relations with them I immediately shifted to a VPS at X10. It too costs me same, around 35$ per month with more RAM and more Disk Space.

    However do not move to a VPS because you want to. It takes a lot of hard work to set it up and maintain it further. You basically have no support what so ever. Your mails not going, file not loading, server down, database not working. No one is accountable for that except you. But then you get all the controls on various configuration files which means you can fine tune the system to meet your needs.

    However one thing which I miss is the comfort of CPanel which used to come in by default with free host and shared hostings. I got so used to it in last 1 year.  Plus being from ECE background doesn’t helps me a great deal either. Anyways I suppose I am here to stay on VPS for long. I am slowly migrating all my websites to VPS. 

I guess this is all I had to share here in this post. If I have missed out on anything which many of you have asked me on chat and mails kindly feel free to ask it here. If I feel I need to add anything, will do so.

For experienced developers who accidentally read till here, feel free to add anything you want to. If you feel anything was wrong in my methodology and approach do let us all know. I am still learning.

All the best for all those starting out there.

Patience is the Key I will say finally.

——————————————————————————-
Other Posts you may want to read:
——————————————————————————-

How to configure Ubuntu and LAMP on Windows

Hello all Linux freaks,

Having already looked upon how to configure Apache-PHP-MySQL on Windows, now here I will try to explain in short how to do the same on Linux OS. I personally don’t have a seperate machine for linux. I run Ubuntu on my Windows machine using VM Ware. So before we go on to see how to configure LAMP on Ubuntu, lets see how can we have Ubuntu running on Windows.

  • For this tutorial I have used VMware-player-2.0.2-59824.exe for VM Ware installation and Ubuntu-7.04-desktop-i386.zip for Ubuntu. You will need to download the same from http://www.vmware.com/download/player/ and http://www.ubuntu.com/GetUbuntu/download
  • Install VM Ware, which is the most simple installer as you can get. At the end it will ask you to reboot the machine and kindly do not skip this step.
  • Now, open VM Ware which you have just installed and you should see something like this:

  • Now click the open button and browse to the folder where you have unzipped the Ubuntu zip file.

  • Click open Ubuntu-7.04-desktop-i386.vmx and thats it. You have just installed and configured Ubuntu on Windows. Simple, Isn’t it ? You should be seeing something like this by now:

For my system, Ubuntu automatically picked up various internet settings. However when I tried running the same from my office, I had to make appropriate changes for proxy setting. Kindly do the same for running internet on your Ubuntu.

Now an important thing before we proceed:

  1. The default administrator password for Ubuntu is ubuntu
  2. By default you are not the admin or root user. Hence you will need to prefix sudo or su to run a command as administrator in the Ubuntu terminal.

Also, before we proceed further kindly check if your Ubuntu is configured correctly for internet connection. Just check by opening this blog through mozilla in ubuntu. If it works, you are all set to configure LAMP on ubuntu.

Follow the following steps to configure LAMP on ubuntu (you need to run a few commands on your terminal window)

  • Open file at /etc/apt/source.list and uncheck the box for install from CD. This will let ubuntu install all modules directly from the repository.
  • $ sudo apt-get upgrade
  • $ sudo apt-get update
  • $ sudo apt-get install mysql-server mysql-admin apache2 php5 libapache2-mod-php5 libapache2-mod-auth-mysql php5-mysql phpmyadmin
  • $ sudo mysqladmin -u root password [YOUR_NEW_PASSWORD]
  • $ sudo /etc/init.d/mysql restart
  • $ sudo /etc/init.d/apache2 restart

Thats pretty much we need. Now let us test our configuration and LAMP setup.

  1. $ sudo vim /var/www/phpinfo.php
  2. Type in the following few lines of code in the file:
    <?php
      phpinfo();
    ?>
  3. Open up your browser and type in http://localhost/phpinfo.php
  4. If you are able to see the php config file information on your browser. Thats it.
  5. Next type http://localhost/phpmyadmin
  6. Login as root i.e. Username : root and Password : [YOUR_NEW_PASSOWRD]
  7. If you are lucky enough you will see the phpadmin console.

Congratulations ! Thats pretty much what exactly we need. Now go on to do all your web development on Linux. Hail Windows 😉

I configure all this stuff long back, so if I have missed out on some issues kindly lemme know and comment the same.

Web Development – Part 1: Apache, MySQL, PHP

Hello Friends,

Ever since I have started web development and launched Altertunes, many of my friends have asked me, “How and Where to start web development ?” . Though there are infinite tutorials over the internet on web development, I will try to jot down my experiences and learnings here.

To start with, I will just try to explain a few terms, before we go on and learn how to handle and integrate them together:

  1. Apache: is the web server, which is used world wide for web development. Since April 1996 Apache has been the most popular HTTP server on the World Wide Web. However, since November 2005 it has experienced a steady decline of its market share, lost mostly to Microsoft Internet Information Services. As of April 2008 Apache served 50.42% of all websites.
  2. MySQL: is a multi threaded and multi-user SQL database management system, which has more than 11 million installations. MySQL is popular for web applications and acts as the database component of the LAMP, BAMP, MAMP, and WAMP platforms (Apache-MySQL-PHP/Perl/Python on Linux/BSD/Mac/Windows), and for open-source bug tracking tools like Bugzilla. It’s popularity for use with web applications is closely tied to the popularity of PHP and Ruby on Rails, which are often combined with MySQL. PHP and MySQL are essential components for running popular content management systems such as Joomla, WordPress, Drupal, and some BitTorrent trackers. Wikipedia runs on MediaWiki software, which is written in PHP and uses a MySQL database.
  3. PHP: is a widely-used, general-purpose scripting language that is especially suited for web development and can be embedded into HTML. It generally runs on a web server, taking PHP code as its input and creating web pages as output. It can be deployed on most web servers and on almost every operating system and platform, free of charge. PHP is installed on more than 20 million websites and 1 million servers, although the number of websites with PHP installed has declined since August 2005. It is also the most popular Apache module among computers using Apache as a web server. The most recent major release of PHP was version 5.2.6 on May 1, 2008.

In short, Apache is the web server which serves the web pages for the website. MySQL is the database which is used to store necessary information ranging from user’s data to user’s pictures. PHP is the server side scripting language used to make web pages. Apache server takes PHP code as input, and outputs an HTML page on the browser.

Lets start some installations and configurations: If you don’t want to handle the installations and configurations of WAMP (Apache-MySQL-PHP on Windows), you may choose to download and install the pre-packaged installer from here. However its always better to configure things yourself to know the inner details. If you are brave enough to install and configure these modules, here we go:

  • Apache Installation: Go to http://httpd.apache.org/download.cgi and download the latest Win32 Binary including OpenSSL (MSI Installer) version of Apache Server Installer Available. Double click the installer and you should see something like this:

    Click next and after a few clicks you will be asked for the following parameters:

    Fill in the details, as shown in the figure above , choose installation type as ‘Typical’ and proceed to install the Apache server.

    Open up your favorite browser and type in http://localhost. If you see a page that says “It works!” then the Apache server has been installed successfully.

  • PHP Installation: Go to http://www.php.net/downloads.php and download the latest PHP Zip Package. Unzip the file into your C: drive, and rename the folder to C:PHP. Next copy the file C:PHPphp.ini-dist file to C:Windows and rename the file it C:Windowsphp.ini. This is the PHP Configuation file where we will be setting some of the important parameters later on.Now its time to integrate PHP with Apache we installed earlier. Open the Apache configuation file (Important: you should always have a copy of this file stored somewhere else, because an error or misconfiguration can cause your Apache server to crash!), which is located at C:Program FilesApache Software FoundationApache2.2confhttpd.conf into notepad and copy the following lines at the end of ‘LoadModule’ section in the configuration file:

    #AddType application/x-httpd-php .php
    LoadModule php5_module “C:/PHP/php5apache2.dll”
    AddType application/x-httpd-php .php .phtml .inc .php3
    AddType application/x-httpd-php-source .phps
    # configure the path to php.ini
    PHPIniDir “C:/Windows”

    Now lets configure the root directory of our Apache server. Root directory is the base directory from where the website is served. When you type in http://localhost in your browser, the server looks for the necessary files in the root directory and serves it to the browser. By default, the root directory of the Apache server is set to : C:Apache2htdocs. You may keep the root as C:Apache2htdocs or you may change it to a directory of your choice as follows:

    Look for the ‘DocumentRoot’ Section in the Apache configuration file located here: C:Program FilesApache Software FoundationApache2.2confhttpd.conf. You should see something like this:

    # DocumentRoot: The directory out of which you will serve your
    # documents. By default, all requests are taken from this directory, but
    # symbolic links and aliases may be used to point to other locations.
    DocumentRoot “C:Apache2htdocs”

    Change C:Apache2htdocs to a directory of your choice, anywhere on your computer. For eg. C:Workspace.

    Further scroll down in the httpd.conf file and search for a section which looks like this:

    # This should be changed to whatever you set DocumentRoot to.
    <Directory “C:Apache2htdocs”>

    Change the directory location from C:Apache2htdocs to whatever you have set in the step before.

    Now to test whether everything is configured correctly, create a file in the root directory of Apache server, named phpinfo.php and paste the following code into it:

    <?php phpinfo(); ?>

    Restart your Apache server from here Start > All Programs > Apache HTTP Server > Control Apache Server > Restart, and open the following URL in your browser: http://localhost/phpinfo.php . If everything is well setup and you are lucky enough, you will see something like this:

    Finally, we just need to make a few configurations in the PHP configuration file which we copied to C:Windowsphp.ini. Open the file in a text editor and find the section which looks like this:

    ; Directory in which the loadable extensions (modules) reside.
    extension_dir = “./”

    Change it to look like this:

    ; Directory in which the loadable extensions (modules) reside.
    extension_dir = “C:PHPext”

    Also, find the section in your PHP configuration file which looks like this:

    session.save_path = “/tmp”

    and change it to:

    session.save_path = “C:WINDOWStemp”

    And finally we come to the end of PHP installation section. Congratulations, Good going !

  • MySQL Installation: Go to http://dev.mysql.com/downloads/mysql and download the latest MySQL database. Once ZIP file has finished downloading, extract it using WinZIP or a similiar program on your computer. Double click the setup.exe file to start the installation. You should see something like this:Keep clicking next and keep all the default options (use typical installation and not the detailed one). After installation finishes, go to start -> run -> services.msc and start the MySQL service. (If MySQL service doesn’t exist, the installation was not successful) . Now we need to tell PHP that MySQL exists on your system, and we need to integrate them. Go to php.ini i.e. the PHP configuration file, and make the following changes:

    Search for something like this:
    ;extension=php_mysql.dll

    and make it like this:
    extension=php_mysql.dll (i.e. you just need to remove the semicolon)

    Additionally you need to add this:
    extension=php_mysqli.dll

    at the end of the extensions. Further copy:
    libmysql.dll to C:WindowsSystem32 and restart Apache.

  • PHPMyAdmin and MySQL Query Browser Installation: Though you can always use MySQL database through command line but having PHPMyAdmin or MySQL query browser will make your database management a lot easier and simple. To install download PHPMyAdmin from here. Download the ZIP file and extract it under the root directory of Apache Server, i.e. if root directory is set as C:Workspace , the extracted PHPMyAdmin folder’s location should have a path C:Workspacephpmyadmin.Open the config.ini.php file in the PHPMyAdmin folder and make the following changes:$cfg[‘Servers’][$i][‘user’] = ‘root’;
    $cfg[‘Servers’][$i][‘password’] = ‘YOUR_PASSWORD’; // Your MySQL Password
    /* Authentication type */
    $cfg[‘Servers’][$i][‘auth_type’] = ‘config’;
    /* Server parameters */
    $cfg[‘Servers’][$i][‘host’] = ‘localhost’;
    $cfg[‘Servers’][$i][‘connect_type’] = ‘tcp’;
    $cfg[‘Servers’][$i][‘compress’] = false;
    /* Select mysqli if your server has it */
    $cfg[‘Servers’][$i][‘extension’] = ‘mysql’;
    /* User for advanced features */
    $cfg[‘Servers’][$i][‘controluser’] = ‘root’;
    $cfg[‘Servers’][$i][‘controlpass’] = ‘YOUR_PASSWORD’; // Your MySQL Password
    /* Advanced phpMyAdmin features */
    $cfg[‘Servers’][$i][‘pmadb’] = ‘phpmyadmin’; //Name of PHPMyAdmin folder
    $cfg[‘Servers’][$i][‘bookmarktable’] = ‘pma_bookmark’;
    $cfg[‘Servers’][$i][‘relation’] = ‘pma_relation’;
    $cfg[‘Servers’][$i][‘table_info’] = ‘pma_table_info’;
    $cfg[‘Servers’][$i][‘table_coords’] = ‘pma_table_coords’;
    $cfg[‘Servers’][$i][‘pdf_pages’] = ‘pma_pdf_pages’;
    $cfg[‘Servers’][$i][‘column_info’] = ‘pma_column_info’;
    $cfg[‘Servers’][$i][‘history’] = ‘pma_history’;

    Now open the url, http://locahost/phpmyadmin and if everything is configured correctly you must see something like this:

And thats it, if you are able to see all the above images on your computer, it means you have just configured everything correctly and you are all setup for web development.

I have installed and configured all the components way back (6 months ago), hence there is a possibility that I might have missed out on some trivial points. If you catch hold of any such issue do comment the same.

Enjoy making cool webpages, and All the best for your website 🙂