PHP Extensions – How and Why?

In this short post we will quickly see:

  1. How to write PHP extensions?
  2. Why to write PHP extensions?

However before you could understand what we are going to disucss, I will recommend you to read one of  my previous post How does PHP echo’s a “Hello World”? – Behind the scene . In this post I discussed in brief the backend architecture of PHP.

Assuming you have read the previous post, lets discuss on how to build our first PHP extension:

  1. Every PHP extension is built out of minimum of 2 files.
  2. Configuration file (config.m4) which tells us what files to build and what external libraries are needed.
  3. Source File(s) which will contain the actual functionalities provided by the extension.

Building a sample extension skeleton
Lets start with building and understanding a sample extension skeleton. Then we will move ahead with building our first PHP extension:


        [Whether to enable the "sample" extension],
        [-enable-sample  Enable "sample" extension support])
if test $PHP_SAMPLE != "no"; then
        PHP_NEW_EXTENSION(sample,sample.c,$ext_shared)  // 1st argument declares the module
                                                        // 2nd tells what all files to compile
                                                        // $ext_shared is counterpart of PHP_SUBST()

I found a number of articles on internet which gives you code for your first PHP extension but none of them go ahead and explain each and every word in those codes. Lets give an attempt in understanding every bit of this strange config file.

  1. This is a minimalistic config file which is required for an extension
  2. The first parameter to PHP_ARG_ENABLE(), sets up a ./configure option called -enable-sample
  3. The second parameter to PHP_ARG_ENABLE() will be displayed during the ./configure process as it reaches this configuration file
  4. Third parameter will be displayed as an option if end user issues ./configure -help

For Newbies: Wondering what is this ./configure option? Kindly read PHP: Installation on Unix System for details.

Lets understand the remaining part of the config.m4 file:

  1. To compile an extension we follow 3 steps: (i) phpize (ii) ./configure -enable-sample (iii) make
  2. When we call ./configure -enable-sample in step (ii), a local environmental variable $PHP_SAMPLE is set to yes. (PS: If our extension name was Hello, then $PHP_HELLO would have been set to yes)
  3. PHP_SUBST() is a MACRO similar to AC_SUBST() in C and is necessary to build the extension as a shared module
  4. PHP_NEW_EXTENSION() declares the module and tell source files that must be compiled as part of the extension. $ext_shared is a counterpart of PHP_SUBST() and is necessary for buildin an extension as a shared module

(PS: We only have a single source file i.e. sample.c for this extension. If in case we had more than a single source file then last line of config.m4 would have been something like this: PHP_NEW_EXTENSION(sample,sample1.c sample2.c sample3.c,$ext_shared) and so on)

Now lets build our source file skeleton. Let’s segregate certain type of data in a header file, which we will finally include in sample.c file. This is generally a good practice rather than maintaining a single source file.


#ifndef PHP_SAMPLE_H
  #define PHP_SAMPLE_H
  #define PHP_SAMPLE_EXTNAME "sample"
  #define PHP_SAMPLE_EXTVER "1.0"

  #ifdef HAVE_CONFIG_H
    #include "config.h"

  #include "php.h"
  extern zend_module_entry sample_module_entry;
  #define phpext_sample_ptr &sample_module_entry

Do not leave this page on seeing this code. It’s all very simple if you have ever written some code in C.
All that this file wants to do is:

  1. config.h file is included when compiled using phpize tool
  2. It also includes php.h from the PHP source tree. With inclusion of php.h, many other .h files also gets included and hence making available a lot of PHP API’s, which can be used by this extension
  3. The zend_module_entry struct is defined as extern so that it can be picked up by ZEND engine using dlopen() and dlsym() functions, when the module loads.


#include "php_sample.h"

zend_module_entry sample_module_entry = {
  #if ZEND_MODULE_API_NO >= 20010901
    STANDARD_MODULE_HEADER,        // Roughly means if PHP Version > 4.2.0
    PHP_SAMPLE_EXTNAME,        // Define PHP extension name
    NULL,        /* Functions */
    NULL,        /* MINIT */
    NULL,        /* MSHUTDOWN */
    NULL,        /* RINIT */
    NULL,        /* RSHUTDOWN */
    NULL,        /* MINFO */
  #if ZEND_MODULE_API_NO >= 20010901
    PHP_SAMPLE_EXTVER,        // Roughly means if PHP Version > 4.2.0
  ZEND_GET_MODULE(sample)      // Common for all PHP extensions which are build as shared modules

Thats it! We have our first PHP extension ready. Compile this module as discussed above i.e.
(i) phpize
(ii) ./configure -enable-sample
(iii) make
check your phpinfo() and see if you have an extension called “sample” loaded successfully or not.

Though this extension is capable of doing nothing, but the skeleton here is the base for every PHP extension. Lets recap in short what has happened till now:


  1. config.m4 file is the configuration file for extension
  2. It declared the extension, tells what all files are required for the extension to build, add a few ./configure -help options too
  3. On the other hand sample.c and php_sample.h are the main source files.
  4. The header file includes the config.h and php.h header files from PHP source tree, which additionally provides a number of PHP API’s which can be used
  5. As discussed in last blog post, every extension have the following modules: MINIT, RINIT, RSHUTDOWN, MSHUTDOWN. sample.c helps in telling PHP, which part of the code corresponds to the above module
  6. For our extension “sample” we have defined NULL as MINIT, RINIT, RSHUTDOWN and MSHUTDOWN and hence this module isn’t capable of doing anything

Building a Hello World Extension
To build an extension which actually do something, we will need to just tweak the abiove skeleton. Here we are trying to build an extension which will provide us with a function called sample_hello_world(), which we can use directly in our php codes to output Hello World!

Quickest link between userspace and extension code is the PHP_FUNCTION(). Start by adding the following code block near the top of sample.c file just after
#include “php_sample.h”

PHP_FUNCTION(sample_hello_world) {
  php_printf("Hello World!n");

PHP_FUNCTION() is basically a MACRO which expands internally. (I will skip this expansion as of now to keep this post as simple as possible)

But simply declaring the function isn’t enough. The ZE needs to know the address of the function as well as how the function name should be exported to the userspace. Place the following block of code immediately after PHP_FUNCTION() block:

static function_entry php_sample_functions[] = {

The php_sample_functions vector is a NULL terminated vector that will grow as we continue to add more functionality to sample extension. Every function we export will appear as an item in this vector.

PHP_FE(sample_hello_world,NULL) expands to {sample_hello_world, zif_sample_hello_world, NULL} and hence providing a name and an address to implement it.

Finally simply go to the sample_module_entry struct and replace:
NULL /* functions */ with
php_sample_functions /* functions */

Now simply rebuild the extension and then try this on command line:
$ php -r ‘sample_hello_world();’

If everything was done perfectly, you would see “Hello World!” output on the shell.

PS: In this tutorial I have tried to explain each and every line which is involved in making a hello world php extension. However I am sure that many questions are still un-answered. Feel free to ask any doubt or correct me in case I have made a blunder while penning this down.

Internship in Swiss : Part 1

One thing which every IITGian starts dreaming about after getting into IIT is a foreign trip in 3rd year. With a strong record being maintained by pass out seniors, every junior have this strong belief “I will get an intern in Europe”

However in past few years the scenario has changed. Students no longer limit their mail spams only to europe. Australia, Brazil, South Africa have emerged as new favorites outside europe. Like many others, I too had this belief and I was one of the luckiest to have got an intern at EPFL, Lausanne, Switzerland.

Though the time when I got my intern at IIT wasn’t a sweet time for me. I was already having a lot of problems due to lack of attendence. However keeping in mind that my BTech project is on Music Information Retrieval and I have got an intern in one of the best universities throughout the world in field of Speech and Music Technology, I decided to move ahead with the Internship. However, this was not the only reason for me to fly all the way to swiss. After a lot of effort and spamming, Sowmya too got an intern at Zurich, Swiss. Now how could we miss that.

For my juniors who keep bombarding me with several question about internship at EPFL. 1500 Swiss Franc per month (+ 500 swiss franc for airfare) is the standard scholarship given by EPFL to students from all IIT’s. (I knew a few from IITB were even getting more). For apartments and living, the best thing is to contact secretary of your professor, which can assist you to getting a cheap apartment. (PS: Do not forget to ask her to contact you before fixing an apartment. In my case the secretary booked a 1500 Swiss Franc per month apartment to be shared with another guy from IIT Bombay. While I can easily remember Himanshu Nazkani getting an apartment for just 450 Swiss Francs per month)

I was quite excited as I was flying out of india for the first time and that too swiss. Had to apply for a tatkal passport which one can easily get in 7 days after showing the internship offer letter to the passport office. I took the Alitalia flight from New Delhi, which was supposed to make a stop in Italy before arriving at Geneva. I was like “wow” all the way. The scenic beauty and the professionalism in foreigners (on duty at airport) was amazing. At this point I could recall me eating beef accidentally while moving from Milan to Geneva.

I reached my apartment after some hustle. My airbag wheels were broken and I had to drag my airbag (Full of rice,sweets,namkeen and what not) for about an hour before I could find my apartment. The apartment was a full suit and was way above expectations. I and Nitin (my roommate from IITB) decided not to change the apartment and continue with it inspite of heavy rent. One thing I would like to suggest is do not carry rice, cereals and other food items with you. You get them easily all around switzerland and at a cheap price. However it is good to carry some utensils if you can. Me and Nitin already decided upon who is going to get what utensils and that really saved us from starving for 3 months. With a cooker and frying pan, I could see the cook in me trying to explore, and believe me I was able to serve my roomy with some classy food for 3 months.

Next day I went to EPFL and met my guide. I was amazed to see the professionalism with which they used to work in the laboratory. My mentor used to code at such a pace, that I can’t even chat at that pace. For use it was like Orkut (becoming popular then), Gtalk, Yahoo Messengers full day. Throughout the week we used to plan for a trip and on weekend enjoy the trip. Swiss means you can’t sit back coding in the laboratory. I saw some of the most beautiful places and girls for 3 months. Lausanne, Zurich, Burkliplatz, Fribourg, Mt. Titlis, Pilatus – Luzern, Geneva, Ouchy, Raperswill, Uetliberg, Felsenegg are a few place which we visited.

As I just recall a bit more on this memorable trip, I will leave you with more than 200 captivating images from our trip of Mt. Titlis (10,000 feets above sea level)

Keep glued and do not forget to leave a comment.

Life in Bangalore after IIT Guwahati

Bangalore, Bangalore, Bangalore !!!

This was what everyone wished for in their final year at IIT Guwahati. Everyone wanted to get a job in one of the multinational firms in Bangalore and like everyone else, this was what I longed for and got too! After a long wait for my joining letter,  I was finally asked to join my present employer on 21st June, 2007 and if I can recall correctly, it was on 19th June, 2007 that I landed in Bangalore.

First trip to Bangalore (2002):
It wasn’t for the first time, that I was visiting Bangalore. I came to Bangalore way back in 2002 for an NDA (National Defence Academy) SSB Interview. That trip was my first trip outside Lucknow (my hometown) and it proved to be a disaster for many reasons:

  • I wasn’t selected in the Indian army.
  • I watched 4 movies in a span of 7 days here in Bangalore. ‘Lagaan’ and ‘Gadar’ were watched back to back on the very first day in Bangalore followed by another one starring Amitabh Bachaan, Manoj Bajpai and Raveena Tandon (I can’t recall its name). Must be wondering how watching movies could have made this trip a disaster. Wait, read on to know about my last movie on that trip.
  •  On the last day, I was already out of the NDA campus roaming on the streets at around 04:00 PM, when I cared to take a look at my train ticket back to Lucknow. The train was scheduled for 08:00 PM . So at 05:00 PM, since I had a lot of time at hand,  I wondered why not watch another movie, probably an english one, at one of the theaters near the railway station. It was ‘The tailor of panama ‘ that I chose to watch. The movie, starring Pierce Brosnan,  was as good as expected. It was about 07:00 PM when I came out of the movie hall. I rushed to the station and sat there awaiting the train’s arrival.  I continued to wait for the train, but till 08:00 PM, neither could I see any rush on the platform nor were there any announcements for that train. I called back home to my father to check if there were some changes in the train schedule. He asked me “Why are you out of the train ? You must be at Hyderabad station right now, isn’t it ?” Foxed on hearing what he was saying, I told him “I am still in Bangalore waiting for the train, but there is no announcements or anything what so ever.”  I had begun to sense that I’d committed some blunder. After the conversation with my father, I realized that the train was at 05:00 PM (the time i decided to watch a movie) and not 08:00 PM. I just put down the receiver and started looking at the ticket for that magical 08:00 PM, how could I mis-read such a thing, and I realized that the train ticket was booked at 08:00 PM in Lucknow, and that was what I interpreted as the train departure timing. Hell of a mistake!
  • But that disaster trip was not going to end here. The ticket stubs of the movies I watched during my stay at Bangalore  were all there in my back pocket. I reached home and my father got hold of those movie tickets. Thats when the real drama started, I was beaten to pieces.

First few days on my second trip:
Anyways, I expected a lot better experience in Bangalore this time. Hotel Orchid Harsha, was where we were supposed to stay for the initial 15 days. All the expenses were managed by the company so we all spent like a millionaire at Harsha. There were atleast 8-10 friends and colleagues present for dinner at the hotel room. 😉 I will say that those 15 days were one of the best here at Bangalore till date, when we lived life King size.

Dull, boring and Monotonous life:
However, once we were all engaged into our professional lifes, we could hardly find time for regular bakarchodi sessions we used to have back in college. It was more of a dull, boring and monotonous life for us all here. Also few of our friends found girl friends for themselves which didn’t help any further (less people = less bakarchodi). 😛 At times, a long drive on bikes with friend (Tau, a huge enthusiast for such long drives, owns a Karizma and 2 accidents till date did not lessen his spirits. Infact he’s looking forward to Hayabussa!) was another thing we tried, but our laziness and eagerness to sit in one position 😛 killed the interest in those long drive trips. Every friday, rock music and drinks at Purple Haze was the only joy we used to have then. Back in college, I used to think that we were not addicted to alcohol and that we used to drink for fun. But after coming to Bangalore I realized that we all had become addicted to beer and hard drinks at some level or the other.

No Rock band for me:
I came to Bangalore with high expectations of forming a new rock band. However it is really disappointing that I couldn’t find a band till now. All the bands from where I got invitation to play were either 20-25 Km from my house or they were not according to my taste or they were just on the starting to play rock music. Involvement with my website ‘’ also didn’t leave me enough time to play my guitar at home.

Work @ Office:
I was probably looking for a different domain in my first job. Business intelligence was probably not the thing for me. (Though the field is great with some great scope ahead in the market) .Knowledge gained while developing my website eventually helped me in cracking Yahoo! . I just hope it will be great fun at Yahoo. Looking forward to working there !

Colleagues @ Office:
One of the things to cheer about is the team and colleague I got to work with at Oracle. Mahesh, Eshwar, Prashanth, Karthik, Vinnet Jain (mantri), Yasser, Vineet Alagh, Ankur and Avisek (Dada), everyone just made sure that I had a rocking and comfortable time at Oracle. Be it the moon walks in the lift by Ankur Jain, Finance funde by Dada or mimicry by mantri, it was fun all the way. The managers had an inspirational presence in the office, seeing them handle and managing thing was a great learning experience in itself. Kumar, Bala, Vishy and Michelle all were inspirational and joy to work with. Overall, I must say that I couldn’t have asked for a better work culture in my first job.

To be continued ….

Bookmark and Share

Me, Music and Guitar : How it all started : Part 1

A things I can’t live without, apart from my parents, love and friends will be guitar and music that will make to the list.

But I was never a born musician. There were friends of mine (Amit Chandra aka Candy and Navneet Singh aka Noni) from school days who used to play old country stuff along with Lucky Ali and K.K. but I was always a part of audience then.

My first real introduction to music was done while I was preparing for JEE examination (25th December 2002). By then Candy and Noni had moved from the world of Lucky Ali to Metallica, Iron Maiden, Aerosmith and the likes. One day after my coaching classes, as I entered Candies house I found a lot of noisy stuff going inside. Actually they were listening to Fly Away by Aerosmith. At that stage I was just like any other normal person without a bit a of knowledge about music. I couldn’t even play Sa,Re,Ga,Ma on guitar or infact any instrument. I asked them ‘Whats the big deal in this song?’. They laughed at me and asked to sing the song for them, as they were planning to form a rock band. Well I was unaware of the world of music, scales, pitch started murmuring the lyrics of the song in my own tune and pitch. I can still recall the way the laughed at me after I sang the first line of the song ‘Gotta find a way’. Actually I sang something ‘Gaataa find a way’ in old dehaati style.

That was my first encounter with the world of music. They gave me a CD full of rock songs and asked me to listen to it. Slowly and steadily, out of what reason I liked the songs, specially ‘Smells like teen spirit by Nirvana’. Candy and Noni looking to form a band turned to me. They initially thought of training me as a drummer and for about 15-20 days I was official drummer of the band . Candy being as Vocalist/Bass/Guitarist and Noni with Vocals/Leads. Anyhow they soon realized the mistake they made by making me a drummer and Candy took my place and I moved to bass guitar.

Fortunately I got selected in JEE and touch wood I got Guwahati. A place you can associate with rock music.There I met some of the best buddies in my life. Special mention to Vikram Batra, Varun Chaudhary with whom I spend many jam sessions. We all entered IIT Guwahati as a novice in music but we made sure by 4th year that our music has the power to capture the rock power.

I formed rock band “Ichor” back in IIT Guwahati with Varun Chaudhary. Till then back in lucknow Navneet formed a band called “Aaveg” and also earned some great name in the field of music and rock guitaring.

m/ Rock On m/

How to integrate Google Friend Connect – In Pictures

I am probably one of the luckiest (if this is the case) to have got google friend connect invitation a couple of minutes back. And it really took me a few minutes (< 10) to setup Google Friend connect on Gtalkbots.

In Pictures:

Try out, if it clicks for your and others, you might get loads of traffic.