Author Archive

yet another ~./vimrc

set tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab number
nnoremap <F7> :tabp<Enter>
nnoremap <F8> :tabn<Enter>
nnoremap <F6> :bd<Enter>
nnoremap <F5> :tabnew<Enter>

set sessionoptions=blank,buffers,curdir,folds,globals,help,localoptions,options,resize,tabpages,winsize,winpos

Create Session:
:mksession /path/to/session/file.vim

Restore Session:
$ vim -S /path/to/session/file.vim
:source %


Possible interview questions for a Senior PHP Web Developer

Below is just an informal list of possible questions to ask a more advanced PHP web developer. Please feel free to add more.
dns port?
SSL port?
what does the linux command dd do?
what does the linux command df do?
how many bits is an IPV6 address?
how many bits is an IPV4 address?
what's a factory?
what's a fascade? can you please give an example of when you would use one?
can you please explain, in simple terms using the whiteboard if necessary, what a reverse proxy is?
what are the four contexts in an nginx configuration file?
what git command would I use to remove all untracked files, ignored files and modified changes?
what git command would I use to update all submodules referenced in a project?
in php, please give two examples of methods that can be used to compensate for multiple inheritence
what is dependency injection? why would it be used? what are its advantages and disadvantages? 
please explain to us, in simple terms, what a IP bit mask is
what are four http headers used for caching?
can you name some alternative methods for caching?
can you please explain to me, as if I were an intermediate programmer, some of the gotchas of developing for web applications with more than one web server?

what is your preferred php library for image manipulation?
have you ever configured a load balancer?
have you ever written a php extension?
how many times have you compiled php from scratch?
how you used redis? can you explain what redis is and when you'd use it?
how familiar are you with web analytics?
can you please write a regular expression for me that will match a string starting at the beginning of the line, followed by five numeric digit, followed by any number whitespace characters, followed by a hyphen, followed by any number of whitespace characters and capturing the rest of the content of the line in a capturing group?


Drop Column If Exists in MySQL

IF EXISTS ( SELECT * FROM information_schema.columns WHERE table_name = 'country' AND column_name = 'created_at' AND table_schema = DATABASE() ) THEN
    ALTER TABLE `country` DROP COLUMN `created_at`;
Because DROP COLUMN IF EXISTS isn't supported by MySQL.


Show All Columns on a MySQL Table

SELECT * FROM information_schema.columns WHERE table_name = ‘my_super_table_name’ AND table_schema = ‘my_super_database_name’;


Show All Indexes on a MySQL Database

SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, CARDINALITY, INDEX_TYPE FROM information_schema.statistics WHERE INDEX_NAME != ‘PRIMARY’ AND table_schema = ‘my_super_database’;


Getting Started with Git

Below are some helpful links and tips for getting started with the Git version control system.

Git is rapidly becoming one of the most widely used version control systems is use today. Git is especially is open source projects as it allows for rapid merging: a feature not found in most version control systems. Git is also compact and FAST.

If you’re a developer, I encourage you to write open source software as a means of deliberate practice. Using Git in the context of open source will really help other contribute and use your work. I recommend specifically. Even professionally, I think that Git’s market share will continue to rise and be more prevalent in the workplace.

After using subversion for years, I dropped it in favour of Git. And below are a few notes that I learned along the way that may make it easier for you to get started. I hope you find using as fun as I do.


Here’s an excellent intro video. You should probably watch this first. There are two parts.

Here’s a nice, short book on how GIT works. You may want to come back to this after you’ve played with the commands for a couple of days. But I do recommend coming back to it. It has lot of explanations that show how git works. I personally read this first. After reading it, I had a great grasp of the concepts which made it easier to memorize the commands.

//see my git links on my delicious account (note: there are 3 pages; some of the more useful ones are older links; the newer links are more advanced items, so you may want to skip them for now)

//Install Git on Ubuntu
sudo apt-get install git-core


Finding the Usage

//Run: git <command> –help to see usage on that command
//eg. git push –help

Some Common Commands

git clone -o github_remote

git pull github_remote

git push github_remote github_branch_master

git push –all github_remote

git status

git commit -a -m “Fixed error with homepage not displaying the correct timezone.”

git add -i


//warning: destructive (like an svn revert); know what you’re doing first with this.

git reset –hard master

//add this bash alias to your ~/.bashrc file to be able to recursively add empty directories to a repository

alias git_add_empty_dirs=’find . \( -type d -empty \) -and \( -not -regex ./\.git.* \) -exec touch {}/.gitignore \;’

//turns on the shell colors for all working copies

git config –global color.ui always

//makes git status = git st

git config –global status

//create an alias to easily recursively update the submodules within a project

git config –global alias.subup “submodule update –init –recursive”

More Useful Git Resources

For people who have used SVN:

A Simple Workflow for using GIT in small teams

Also, the git official website has a lot of resources…

Here’s a great article on rebasing:


Create your own linux/mysql/php development box for Windows or Mac OS X

Download iso of ubuntu server edition 11
Download VirtualBox

Install VirtualBox
Create a new VM with 1000mb ram and 20GB of storage
	- bridge the network connection
	- default install (enable openssh server)
$ sudo su -
$ visudo
$ vim /etc/network/interfaces
	auto eth0
	iface eth0 inet static

$ /etc/init.d/networking restart
$ ifconfig
$ ping  //confirms internet connectivity
$ apt-get update  //update package manager sources
$ apt-get install mysql-server  //install mysql
$ apt-get install apache2
$ apt-get install php5
$ php -v  //confirm php 5.3.5
$ apt-get install samba  //install samba
$ vim /etc/samba/smb.conf
	- enable (uncomment) [homes]
	- read only = no
	- create mask = 0775
	- directory mask = 0775
$ sudo smbpasswd myusername
$ /etc/init.d/smbd restart //restart samba service to apply changes
	- should be able to connect to your smb share via windows or mac (
$ apt-get install git-core


Export to CSV with MySQL

On Ubuntu, this will create a file in /var/lib/mysql/[DB_NAME]/output.csv

I had to run the query as MySQL root. Didn’t try to find out what permission actually permitted the user to write to the file. It’s probably create table though.

SELECT, v.title,, v.slug, v.description
video v
video_category vc ON v.video_category_id =
OUTFILE 'output.csv'


Using C++ With PHP

UPDATE: I’ve since found a good github project to use C++ within a PHP extension (
The following article is a bit outdated.

Reproduced from because I didn’t want to lose this information. I will modify it to be more clear as I explore more on this subject.

Before We Begin

Before we begin, I should note that the focus of this article will be on the UNIX side of the PHP world. I’ll mention a few pointers for Windows development, but since I do most of my coding on UNIX systems, I’ll be sticking to what I know for the most part.

I should also mention that these instructions should work with PHP 4.2.x and 4.3.x.

Now, here’s a few conventions I’ll use throughout this article…

  1. $PHP_HOME will refer to the path to your PHP source code, i.e. where you unpacked your PHP source. On my system, it’s /home/jay/setup/php/php-x.x.x.


  2. The example module we’ll be creating will be called cppext.

    The Setup

    Before you get to coding your extension for PHP in C++, you’ll need to get yourself a basic extension skeleton. In the UNIX world, you’ll want to run a shell script found in $PHP_HOME/ext called ext_skel. Switch over to the $PHP_HOME/ext directory and fire up the shell script. Use the --extname argument to give your extension a name.

        jay@monty ~ $ cd setup/php/php-4.3.1/ext
        jay@month ext $ ./ext_skel --extname cppext

    On Windows systems, there’s PHP script in $PHP_HOME/ext called ext_skel_win32.php in the current PHP CVS HEAD. It’ll probably become a part of PHP 5 and may be included in future versions of the PHP 4.x branch. I have no idea if it works, but the daring may try it out…

    You should now have a basic PHP extension ready to go in $PHP_HOME/ext/cppext. The only problem is, it’s all done in C and not in C++.

    Setting Up The config.m4 File

    Now would be a good time to open up your extension’s config.m4 file and get it ready for some C++ action. This section is geared towards PHP 4.2.x, but it should still work in PHP 4.3.x.

    There isn’t much you have to change here. Basically, you want to tell PHP’s build system that it should be prepared to use C++ and link with the standard C++ library. Here’s a sample file for our little cppext extension, minus all of the auto-generated comments:

        PHP_ARG_ENABLE(cppext, for cppext support,
        [ --enable-cppext            Enable cppext support]
        if test "$PHP_CPPEXT" != "no" ; then
            PHP_EXTENSION(cppext, $ext_shared)

    In PHP 4.3.x, the config.m4 file can be set up a little differently, but the above should still work fine.

    Setting Up The File

    Now you’ll need to set up the file. In PHP 4.3.x, this file won’t exist, so you’ll have to create it. The build system in PHP 4.3.0 got rid of this file, but it will still work.

    In this file, you want to tell the build system which files it should compile using your C++ compiler. There’s not much difference as compared to the stock that ext_skel creates in PHP 4.2.x…

        LTLIBRARY_NAME          =
        LTLIBRARY_SOURCES_CPP   = cppext.cpp
        LTLIBRARY_OBJECTS_X     = cppext.lo
        include $(top_srcdir)/build/

    Setting Up The Source

    With config.m4 and in place, you can start setting up your code. Rename cppext.c to a more Cish name. Following our example, rename it to cppext.cpp.

    Now you can start editing the file. If you were to try and build the extension in it’s current state, odds are it would compile without any errors as a shared object, but it probably would not work with PHP. If you compiled it statically into PHP itself, you’d probably get some linker errors. This is due to various differences in C (which is what PHP is written in, for the most part) and C (which is what your extension will be written in). Think name mangling and that sort of thing.

    To remedy this, you’ll need to tell your extension to treat a few PHP API functions as if they were written in C (which they are) rather than in C (which they aren’t).

    You’ll need to wrap a few lines with BEGIN/END_EXTERN_C(). Specifically, you’ll want your cppext.cpp to look like this:

        extern "C" {
        #include "php.h"
        #include "php_ini.h"
        #include "ext/standard/info.h"
        #ifdef COMPILE_DL_CPPEXT

    Normally, we’d want to wrap the header files above in BEGIN/END_EXTERN_C() as we did for ZEND_GET_MODULE(cppext), but since BEGIN/END_EXTERN_C() are defined in zend.h, extern "C" will have to do.

    In Windows, you may find that Visual C complains about linking your extension. You may need to put something like this near the top of your extension:

        #ifdef PHP_WIN32
        #include <iostream>
        #include <math.h>

    That seems to help. You should obviously put that in there anyway to try and keep things cross-platform.

    Compiling the Extension

    Now you’re ready to compile your extension. If you want to compile the extension statically (compile into PHP as a part of PHP itself), go down to the PHP root directory at $PHP_HOME, move the configure file out of the way and run buildconf.

    Next, run configure with your normal set of configuration options and add --enable-cppext. Run make clean, make, make install and all that other jazz, like recompiling Apache and all that.

    If you want to compile the extension as a loadable object, head to your extension’s directory and run the phpize command. (This assumes that you have PEAR installed on your system.) phpize will create a configure script just for your little extension. Run configure, make and make install. If you want the extension to load automatically, you’ll have to modify your php.ini file to load the proper file. Adding a line like should do the trick.

    Your extension should now be compiled and ready to use by PHP. Try running the auto-generated cppext.php file found in your extension’s source directory to see if everything is kosher.

    Mapping C++ Classes To PHP

    There are a ton of ways you can go about doing this, but here’s a few tips to get you started.

    • Start of by making a global zend_class_entry for each class. You also need to have a list entry to handle the destructors for your actual C++ objects, which we’ll actually be treating as PHP resources. (See Note 1 in the exmaple code.)


    • Put all of your methods into your function_entry array. For each class, make another function_entry for the methods you want to map. (See Note 2 in example code.)


    • Your MINIT function should initialize the class entries, list entries, etc. (See Note 3.)


    • In your PHP class constructor, you need to register a resource within the PHP class. This resource (handle in the example code) is used to reference the actual C++ object in method calls. (See Note 4.)


    • Map your PHP methods onto the C++ class methods. (See Note 5.)


    That’s pretty much it. Of course, there are a ton of ways to get the same effect, but this one’s pretty simple and should be a decent guide to get you going.

    Example Code

    Here’s some example code to get you going. This is pretty simple stuff — we have a single C++ class that we map to PHP. The C++ class is simple and doesn’t do much, but you should be able to figure out the harder stuff if you can understand this…


        dnl config.m4 for extension cppext
        PHP_ARG_ENABLE(cppext, whether to enable cppext support,
        [  --enable-cppext        Enable cppext support])
        if test "$PHP_CPPEXT" != "no"; then
            PHP_NEW_EXTENSION(cppext, cppext.cpp class.cpp, $ext_shared)

        LTLIBRARY_NAME        =
        LTLIBRARY_SOURCES_CPP = cppext.cpp
        LTLIBRARY_OBJECTS_X =   cppext.lo class.lo
        include $(top_srcdir)/build/

    class.h — this is for our actual C++ class…

        #ifndef __CLASS_H__
        #define __CLASS_H__
        #include <string>
        using namespace std;
        class MyPHPClass
                string itsString;
                MyPHPClass(string s = "default");
                void setString(const string s);
                string getString() const;

    class.cpp — the MyPHPClass implementation…

        #include "class.h"
        MyPHPClass::MyPHPClass(string s)
            itsString = s;
        void MyPHPClass::setString(const string s)
            itsString = s;
        string MyPHPClass::getString() const
            return itsString;

    php_cppext.h — our PHP wrapper header. Be careful with putting actual C++ code in here, as the C compiler used to build PHP may choke on it during static builds.

        #ifndef PHP_CPPEXT_H
        #define PHP_CPPEXT_H
        extern zend_module_entry cppext_module_entry;
        #define phpext_cppext_ptr &cppext_module_entry
        #ifdef PHP_WIN32
        #define PHP_CPPEXT_API __declspec(dllexport)
        #define PHP_CPPEXT_API
        #ifdef ZTS
        #include "TSRM.h"
        static void destroy_myphpclass(zend_rsrc_list_entry *rsrc TSRMLS_DC);
        #ifdef ZTS
        #define CPPEXT_G(v) TSRMG(cppext_globals_id, zend_cppext_globals *, v)
        #define CPPEXT_G(v) (cppext_globals.v)
        #endif	/* PHP_CPPEXT_H */


        #ifdef HAVE_CONFIG_H
        #include "config.h"
        #ifdef PHP_WIN32
        #include <iostream>
        #include <math.h>
        extern "C" {
        #include "php.h"
        #include "php_ini.h"
        #include "ext/standard/info.h"
        #include "php_cppext.h"
        #include "class.h"
        /* Note 1 -- here's the zend_class_entry. You'll also
        need a list entry for the resources used to store the
        actual C++ objects... */
        static zend_class_entry myphpclass_entry;
        static int le_myphpclass;
        /* Note 2 -- all of the methods go into this
        function_entry. Below are the actual methods that
        map onto MyPHPClass. */
        function_entry cppext_functions[] = {
            PHP_FE(myphpclass,				NULL)
            PHP_FE(myphpclass_getstring,	NULL)
            PHP_FE(myphpclass_setstring,	NULL)
            {NULL, NULL, NULL}
        static function_entry myphpclass_methods[] = {
            {"getstring",	PHP_FN(myphpclass_getstring),	NULL},
            {"setstring",	PHP_FN(myphpclass_setstring),	NULL},
            {NULL, NULL, NULL}
        /* {{{ cppext_module_entry
        zend_module_entry cppext_module_entry = {
        #if ZEND_MODULE_API_NO >= 20010901
        #if ZEND_MODULE_API_NO >= 20010901
        /* }}} */
        #ifdef COMPILE_DL_CPPEXT
        /* {{{ PHP_MINIT_FUNCTION
            /* Note 3 -- here we register the destructor for the myphpclass PHP objects,
            which deletes the actual C++ objects. Below that, we initialize the
            class entry for myphpclass. */
            le_myphpclass = zend_register_list_destructors_ex(destroy_myphpclass, NULL, "myphpclass-obj", module_number);
            INIT_CLASS_ENTRY(myphpclass_entry, "myphpclass", myphpclass_methods);
            zend_register_internal_class(&myphpclass_entry TSRMLS_CC);
            return SUCCESS;
        /* }}} */
        /* {{{ proto myphpclass object myphpclass()
            Returns a new myphpclass object. This is basically the constructor. */
            /* Note 4 -- here's the constructor. First, initalize return_value as an
            object, then make a handle to the C++ object. Register the handle as a resource
            and store the resource within the PHP object so we can get to it in the method
            calls. */
            MyPHPClass *obj;
            zval *handle;
            if (ZEND_NUM_ARGS() != 0) {
            obj = new MyPHPClass;
            object_init_ex(return_value, &myphpclass_entry);
            ZEND_REGISTER_RESOURCE(handle, obj, le_myphpclass);
            zend_hash_update(Z_OBJPROP_P(return_value), "handle", sizeof("handle"), &handle, sizeof(zval *), NULL);
        /* }}} */
        /* Note 5 -- this macro gets the resource handle for the C++ object so we can
        use the C++ object in our methods mappings below. */
        #define CPP_GET_THIS() \
            id = getThis(); \
            if (!id) { \
                php_error(E_ERROR, "this isn't an object?! %s()", get_active_function_name(TSRMLS_C)); \
            } \
            if (zend_hash_find(Z_OBJPROP_P(id), "handle", sizeof("handle"), (void **) &handle) == FAILURE) { \
                php_error(E_ERROR, "underlying object missing, can't find 'this' in %s()", get_active_function_name(TSRMLS_C)); \
            } \
            obj = (MyPHPClass *) zend_list_find(Z_LVAL_PP(handle), &type); \
            if (!obj || type != le_myphpclass) { \
                php_error(E_ERROR, "underlying object is of wrong type in %s()", get_active_function_name(TSRMLS_C)); \
        /* {{{ proto string myphpclass->getstring()
            Passthru to MyPHPClass::getString(). */
            MyPHPClass *obj;
            zval *id, **handle;
            int type;
            RETURN_STRINGL((char*) obj->getString().c_str(), obj->getString().length(), 1);
        /* }}} */
        /* {{{ proto bool myphpclass->setstring(string)
            Passthru to MyPHPClass::setString(string). */
            MyPHPClass *obj;
            zval *id, **handle;
            int type, len;
            char *str;
            if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &str, &len) == FAILURE) {
            else {
        /* }}} */
        /* {{{ destructor for myphpclass objects */
        static void destroy_myphpclass(zend_rsrc_list_entry *rsrc TSRMLS_DC)
            delete (MyPHPClass*) rsrc->ptr;
        /* }}} */

Where To Go From Here

Now that you have a working PHP extension written in C++, you can start using all of C++’s features with PHP. Start making some classes, or wrapping PHP extensions around C++ libraries. The possibilities are finite!

For a more advanced example and various C++ tricks like classes, pure abstract virtual stuff and all of that nonsense, you can review the source for a PHP extension I wrote in C++ called cryptopp-php, which can be found at [Removed Broken Link]. There’s plenty in there to see and perhaps get some ideas from.

Have fun with your C++ and PHP, you OOP nut.


Hiphop Benchmarks


Hiphop is Facebook’s PHP compiler. It compiles php source into c++ source. This is my experiment with compiling and running it with a couple of scripts from


I’m using a build at c3876a7dcaf1694f7c23232149df3283753ed9f9 from (Sept 8th, 2010).

I was able to build successfully under ubuntu with the help of this document:

If for some reason make fails, you’ll need to delete the CMakeCache.txt file and build again once you’ve resolved the build error.

On to the benchmarks…

I’m using GNU time for the benchmarks:


# lshw -short
H/W path Device Class Description
system System Product Name
/0 bus A8V
/0/0 memory 64KiB BIOS
/0/4 processor AMD Athlon(tm) 64 Processor 3700+
/0/4/5 memory 64KiB L1 cache
/0/4/6 memory 1MiB L2 cache
/0/37 memory 2GiB System Memory
/0/37/0 memory 512MiB DIMM DDR Synchronous 333 MHz (3.0 ns)
/0/37/1 memory 512MiB DIMM DDR Synchronous 333 MHz (3.0 ns)
/0/37/2 memory 512MiB DIMM DDR Synchronous 333 MHz (3.0 ns)
/0/37/3 memory 512MiB DIMM DDR Synchronous 333 MHz (3.0 ns)
/0/100 bridge K8T800Pro Host Bridge
/0/100/1 bridge VT8237 PCI bridge [K8T800/K8T890 South]
/0/100/1/0 display Radeon RV100 QY [Radeon 7000/VE]
/0/100/a eth0 network 88E8001 Gigabit Ethernet Controller
/0/100/f storage VIA VT6420 SATA RAID Controller
/0/100/f.1 scsi0 storage VT82C586A/B/VT82C686/A/B/VT823x/A/C PIPC Bus Master IDE
/0/100/f.1/0 /dev/sda disk 300GB ST3300831A
/0/100/f.1/0/1 /dev/sda1 volume 276GiB EXT3 volume
/0/100/f.1/0/2 /dev/sda2 volume 2941MiB Extended partition
/0/100/f.1/0/2/5 /dev/sda5 volume 2941MiB Linux swap / Solaris partition


Benchmark 1:



gtime php fasta.php
User: 278.85 System: 1.39 Elapsed: 6:50.66 68%CPU (0text+0data 30000max)k

gtime ./program
User: 190.81 System: 5.64 Elapsed: 6:58.20 46%CPU (0text+0data 1041840max)k

gtime ./build/program > output.txt
User: 199.91 System: 1.05 Elapsed: 3:21.98 CPU: 99% Memory( Avg Res: 0kB Max Res: 1041856kB )

gtime php fasta.php > output2.txt
User: 330.14 System: 1.17 Elapsed: 5:32.78 CPU: 99% Memory( Avg Res: 0kB Max Res: 30000kB )

Both output.txt files are 243MB.

Benchmark 2:



gtime php btrees.php
stretch tree of depth 16 check: -1
65536 trees of depth 4 check: -65536
16384 trees of depth 6 check: -16384
4096 trees of depth 8 check: -4096
1024 trees of depth 10 check: -1024
256 trees of depth 12 check: -256
64 trees of depth 14 check: -64
long lived tree of depth 15 check: -1
User: 40.59 — System: 0.08 — Elapsed: 0:40.89 — CPU: 99% — Max Res Memory: 312944kB

gtime build/program
stretch tree of depth 16 check: -1
65536 trees of depth 4 check: -65536
16384 trees of depth 6 check: -16384
4096 trees of depth 8 check: -4096
1024 trees of depth 10 check: -1024
256 trees of depth 12 check: -256
64 trees of depth 14 check: -64
long lived tree of depth 15 check: -1
User: 9.86 — System: 0.06 — Elapsed: 0:09.98 — CPU: 99% — Max Res Memory: 237152kB


In benchmark 1, Hiphop performed similarly when outputing to the shell, but was 65% faster when output was piped to a file. However, it consumed 3500% more memory than its php counterpart.

In benchmark 2, Hiphop was 411% faster and consumed 75% of the memory that the php version did.

Future Considerations

Hopefully I’ll be able to add more benchmarks as time goes on. Hiphop is still very young and unstable; though, it does show promising results even now.