Installation PHP5-FPM with Apache 2 in Ubuntu 14.04/10, 15.04/10


PHP-FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features useful for sites of any size, especially busier sites.

These features include:

  • Adaptive process spawning (NEW!)
  • Basic statistics (ala Apache’s mod_status) (NEW!)
  • Advanced process management with graceful stop/start
  • Ability to start workers with different uid/gid/chroot/environment and different php.ini (replaces safe_mode)
  • Stdout & stderr logging
  • Emergency restart in case of accidental opcode cache destruction
  • Accelerated upload support
  • Support for a “slowlog”
  • Enhancements to FastCGI, such as fastcgi_finish_request() – a special function to finish request & flush all data while continuing to do something time-consuming (video converting, stats processing, etc.)

Normally PHP FPM is said to be installed with nginx. Apache is a very popular and quite easy to use for most of hte users/developers in any of the platforms/OS (Windows, Mac or Linux). Fortunately it can be installed and configured quite easily with Apache2 too. .


  1. First install normal Apache2
    sudo apt-get install apache2
  2. Now install FastCGI and PHP FPM
    $ sudo apt-get install libapache2-mod-fastcgi php5-fpm

    Note: if libapache2-mod-fastcgi does not work, check your source.list has multiverse is enabled (uncommented).

  3. Then create the file /etc/apache2/conf-available/php5-fpm.conf with the contents:
    <IfModule mod_fastcgi.c>
        AddHandler php5-fcgi .php
        Action php5-fcgi /php5-fcgi
        Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
        FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -socket /var/run/php5-fpm.sock -pass-header Authorization
        <Directory /usr/lib/cgi-bin>
            Require all granted
  4. Then run the following commands:
    sudo a2enmod actions fastcgi alias
    sudo a2enconf php5-fpm
    sudo service apache2 reload

That’s it. You just need now to test it if your configurations are done properly or not. For that, just create a file in /var/www/html/ as info.php in your favorite PHP/TEXT editor and add the following code:

<?php phpinfo(); ?>

Save the file and run it from the browser http://localhost/info.php

If you can see phpinfo() function’s output, then you are done. Start your further developments.

Read More

MySQL Command line login with inline password & Executing SQL Statements

Login with inline password in command line

Normally we don’t need to use inline password to login or we don’t do that. But sometimes it is a must when you need to login from a bash script or when we need to execute some SQL Statements from bash script or run them in a cron. If you check MySQL manual they have just included the simple command :

shell> mysql –host=localhost –user=myname –password=mypass mydb

shell> mysql -h localhost -u myname -pmypass mydb

But when I tried both of them it did not work and the reason seems that my password has special characters in it and it does not work even I put it in double/single quotes like this:

shell> mysql –host=localhost –user=myname –password=”my#some%pass@word” mydb

I try to search in the Google but there was no luck. Everywhere they were suggesting the same as official manual page itself says the same. When I tried myself several ways quoting the parameters and values separately, even that did not work. Finally while trying I ended up with using single quote for both parameter and the value as follows :

shell> mysql –host=localhost –user=myname ‘–password=my#some%pass@word’ mydb

But I did not quote any others but only password section.

Problem: Executing the SQL Statement from Command line itself
This is simple once we know the parameter of mysql command. The parameter –execute is used to execute the SQL statements from command line. But this again needs the inline password to work.

mysql –user=root ‘–password=sdfdsfsdfs’ –database=firsthelp –execute=”UPDATE table SET field=value WHERE 1″

Executing SQL Statement from Cron
Using the same above command we can run it from cron as follows:

30 * * * * mysql –user=root ‘–password=sdfdsfsdfs’ –database=firsthelp –execute=”UPDATE table SET field=value WHERE 1″

This will execute the statement in every half an hour. Or we can create a bash script and run it from cron.

Read More

Using Zend Server’s PHP for Command line (CLI) in Ubuntu 14.10

By default when you install Zend Server, it does not allow to use PHP directly from command line though the configured PHP applications work with web server (Apache or nginx). Try:

$ php -v

It will ask you to install PHP separately.

Though you can install another PHP and use it for all command line scripts but there is a quick work around to use Zend Server’s PHP itself.

I am not sure about other systems but in Ubuntu 14.04 and 14.10 you can add the path in your bash shell i.e. ~/.bashrc or ~/.bash_profile.

Run the following command to add the path:

$ export PATH=/usr/local/zend/bin:$PATH

Then reload the zce.rc located at /etc/zce.rc:

$ source /etc/zce.rc

Loading in /etc/zce.rc sets up the system library path correctly and removes warnings about the crypto lib.

I hope this will help others who have installed another PHP along with Zend Server :-)

Read More

Very frequently used GIT Commands


The steps and commands are all in Ubuntu (Linux) and should be almost same for Mac OS as well but haven’t tested it myself. And GIT server is GitHub itself. I am not going to give any theoretical definitions of anything here. Directly the commands are presented for different purposes.

Clone a Repository

Assumed that you have a repository given of a project. Two different URLs are provided by GitHub HTTPS and SSH. I prefer SSH and for that you need to add the SSH Key of your computer to the GitHub server, please look at the page here for more details about generating and adding SSH Keys to the GitHub. Now to clone the project using the repository. Go to the directory where you want to clone the project. Normally it should be /var/www:

$ cd /var/www
$ git clone <repository_link>

Note: Don’t create the directory because it will create itself

GIT Branching

List branch and check your current branch.

$ git branch



That means you are in dev branch which is with *.

Switching Branch

$ git checkout master

Now your working branch is changed to master.

Create a branch

$ git branch <branch_name>


$ git checkout -b <branch_name> <source_branch>

The later command creates a new branch and switches to newly created branch.

Git Status

Status means to check if there are any changes made in the current repository/branch. To check the status:

$ git status

This will list the added/modified files.

Adding added/modified files

$ git add // or to add all the modified files than just use period (.)

Committing the changes

$ git commit -m “Give some commit message.”

Pull the updates from the server

$ git pull origin dev // get the updates from the server in dev branch, origin is the server name provided by GitHub

Push the commits to the server

$ git push origin dev

So basically when you need to get the updates from the server in a branch, you need to pull and when you need to push the changes that you have made locally then you will have to push it.


Merging means combining one task done in a branch to another. Normally the sub-branches are merged to the main branches. The branches checked out from a branch are sub-branches. For example, if you have taken a branch dev from master and you worked on dev. You need to merge the works done in dev branch to master.

$ git checkout master //<< first checkout to the target branch
$ git merge dev //<< merge the dev branch to master

Conflicts & resolving conflicts

Sometimes conflicts might happen in the files while merging or pulling the updates. Conflicts happens when there are changes in single file in two different branches at once. To resolve the conflicts, one can just open the file and remove/manage their codes but it is difficult to do in that way simply opening the file. Using GIT’s mergetool it is quite easier to resolve the conflicts in GUI. I normally use meld, so if you don’t have one in your Ubuntu then install it:

$ sudo apt-get install meld

Once installed, hit the following command:

$ git mergetool

Please run this command only when there are conflicts. Once you hit this command, you will have a three column editor opened. Three columns contain three copy of the files, base (branch) code, local copy and the remote copy.


Read More

Using phpmyadmin for multiple local and remote MySQL Servers

Normally we need a client software to access MySQL server whether it is remote server or local. Most of the developers who use MySQL as back end database use phpmyadmin which is a web application. But when it comes to access the remote database, we use different client applications. MySQL Workbench is the official MySQL Client application/software which does pretty much good job for most of the cases. That’s why I think most of the developers choose this. In Windows I used to use SQLYog which is not yet free.

When I come to Ubuntu, which is my day to day development operating system, MySQL Workbench really sucks. It crashes everytime when I try to execute even any simple select queries. Several times I have felt it crashes without any notification, warning specially when I am in the middle of execution of UPDATE/INESRT statements. Becuase of this, I have faced problems qutie a lot since long time. Now its time to search for the alternative of it and I found phpmyadmin as a quite better solution for the moment.

Configuring phpmyadmin to manage multiple local and remote MySQL Servers

I assume that web server (Apache), PHP and phpmyadmin are already installed in the machine. phpmyadmin contains a configuration file named in the phpmyadmin’s main folder. Intially if you don’t find this file then you need to copy/rename

First of all lets see the main configurations in this file. The array named $cfg holds all the phpmyadmin’s setting values and $cfg[‘Servers’] contains the different server’s configurations in another numerical index $i:
Initialize the $i index variable for the array, you don’t have to do this but just make sure it exists almost on the top of the server configurations.

$i = 0;

The array for phpmyadmin in this case only works with non-zero numeric index, so lets increment index variable $i and start adding first server information. This first block normally exists there, uncomment if it is commented.

/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'your_db_user';
$cfg['Servers'][$i]['password'] = 'your_db_password';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'your_db_host';

Note: Here the auth_type is for whether you want to enter the username and password or you want directly logged into server without asking to give username and password every time you want to access. So if you want to enter the username and password then make it ‘cookie’ or ‘config’ if you want automatically logged into phpmyadmin without promoting to enter username and password.
Now repeat the above configurations to add other servers:

/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'your_another_db_user';
$cfg['Servers'][$i]['password'] = 'your_another_db_password';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'your_another_db_host';

You can repeat this as many times as you want. Depending upon the auth_type that you set, you will be prompted to select server on the login screen. If not, you will see a drop down on the left frame of the phpmyadmin’s screen to switch the server.

Read More

Installing Percona 5.6 in Ubuntu 13.10 Saucy !

First of all, I would recommend login as root so that you don’t have to sudo every time you hit the command and give the root password.

$ su -

Now you should be logged in as root. Mine now is


Step 1:
First of all lets remove everything that is related to MySQL from the machine.

apt-get remove mysql*
apt-get purge mysql*
apt-get autoremove

Step 2: Adding the key
Now lets add the key that is provided by Percona, we have to add this to be allowed to install from Percona server.

apt-key adv --keyserver --recv-keys 1C4CBDCDCD2EFD2A

Step 3: Adding the repository
Lets add the Percona repository in the sources list in the machine/Ubuntu.

vim /etc/apt/sources.list

Add the following two lines in the source list:

deb saucy main
deb-src saucy main

Step 4: Apt-Pinning the packages
In some cases you might need to “pin” the selected packages to avoid the upgrades from the distribution repositories. You’ll need to make a new file /etc/apt/preferences.d/00percona.pref and add the following lines in it:

vim /etc/apt/preferences.d/00percona.pref

Add the following line:

Package: *
Pin: release o=Percona Development Team
Pin-Priority: 1001

Step 5: Update

$apt-get update

Step 6: Install Percona Server and Client

$ apt-get install percona-server-server-5.6 percona-server-client-5.6

Step 7: Install dependencies
If there are any dependencies left, then lets install them

$ apt-get install -f

Step 8: Testing
To make sure if Percona Server is installed in your machine with MySQL simply try:

$ mysql -u root -p

And it showed me :

root@rajug:~# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.6.15-63.0 Percona Server (GPL), Release 63.0

Copyright (c) 2009-2013 Percona LLC and/or its affiliates
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.


That means I have now Percona Server !

Read More

Ubuntu 13.10/14.04 mcrypt missing – Fatal Error: Undefined function mcrypt_encrypt()!

I had updgraded my Ubuntu from 13.04 to 13.10 last week and everything went quite good. The only problems that I faced as developer are:

  1. Apache 2.4 was not working with default previous installation and configuration and I had to remove it (completely uninstall/purge and autoremove) and install it again.
  2. All the virtual host setting did not work. I did not go for opting to change the Include setting in apache2.conf instead I rewrote all the settings myself.
  3. Another annoying and very strange problem was that PHP and its libraries. First I had problems with installing apache module that connects to PHP. Secondly I had problems of missing mcrypt library which is required for couple of projects on my system. Particularly a project developed in Zend 1.11 and phpmyadmin did not work. I had the following error where I had written some methods for AES encryption with PHP’s mcrypt library.
Fatal Error: Undefined function mcrypt_encrypt()

I thought the mcrypt library was missing in my PHP installation and I simply tried to install it via command line as follows:

$ sudo apt-get install php5-mcrypt

And I got the following:

Reading package lists... Done
Building dependency tree       
Reading state information... Done
php5-mcrypt is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 13 not upgraded.

Weird :(. If it is already there why isn’t it working with my projects? Then I Googled for sometime and could not find exact solution anywhere. I tried to look the ini in /etc/php5/conf.d/ and there was mcrypt.ini file with quite proper content in it:

; configuration for php MCrypt module

Again I pulled my hair out and went out for the tea. Then I came and tried to look at the other folders inside /etc/php5 folder and saw there mods-available which had again some ini files in it but missing mcrypt.ini. Then I just tried moving that mcrypt.ini file from /etc/php5/conf.d/ to /etc/php5/mods-available/ then restarting the apache server.

$mv /etc/php5/conf.d/mcrypt.ini /etc/php5/mods-available/

It worked when I tested a test script from command line. But my project still wasn’t working from browser. It kept saying the function is not found.

In order to work it from the browser, Apache should also have mcrypt module enabled. Then I had to enable mcrypt module in my Apache. So I ran the following command to enable it:

sudo php5enmod mcrypt

Now lets restart the apache once again.

$ sudo service apache2 restart

Then I tried phpmyadmin from the browser, amazingly it worked now !

Hope this will help others who are facing the same issue.

Read More

Converting PFX Certificate file to .PEM format in Linux/Ubuntu !

I don’t know if there are other ways to have a .PEM file from a PFX file in Linux (Ubuntu), but after couple of research/study in the internet, I came to find some work around. First of all what those formats are actually, let me explain what I came to understand.

PFX Format
Originally defined by RSA in the Public-Key Cryptography Standards, the “12” variant was enhanced by Microsoft. This is a passworded container format that contains both public and private certificate pairs. Unlike .pem files, this container is fully encrypted. Every time I get one I have to google to remember the openssl-fu required to break it into .key and .pem files.

PEM Format
Governed by RFCs, it’s used preferentially by open-source software. It can have a variety of extensions (.pem, .key, .cer, .cert, more). And in most cases while we need to use the private and public keys together in scripting languages like PHP then we have this format.

Converting PFX file to certificate and key format first
Openssh is the open source application to convert these. The command openssl in Linux comes with lots of other options but we will be using few here:

openssl pkcs12 -in yourpfxfile.pfx -clcerts -nokeys -out desired_certificate_filename.cer

This command extracts public key to desired_certificate_filename.cer.

openssl pkcs12 -in yourpfxfile.pfx -nocerts -nodes  -out desired_publickey_filename.key

This command extracts private key to desired_certificate_filename.key.

PEM File
Now lets combine both into one .pem file.

cat desired_certificate_filename.cer desired_certificate_filename.key > desired_pem_filename.pem

Hope this will help !

Read More

Zend Framework – Using FlashMessenger Helper outside of Controller

I was struggling to check session expiry for Zend_Auth and redirect the users to login page with certain message to let them know the session has expired. Found following code to limit the session expiry time:

$authns = new Zend_Session_Namespace(Zend_Auth::getInstance()->getStorage()->getNamespace());
$authns->setExpirationSeconds(60 * 15); // for 15 minutes

Then the major problem that I encountered while setting the messages using Flash Messenger plugin. Though I am not quite experienced Zend programmer but since last couple months, I had used the Flash Messenger plugin directly from within action controllers. It seems the plugin is automatically loaded in the action controllers. But I was about to check the user’s login session expiry in one of my own custom plugin which extends Zend_Controller_Plugin_Abstract as follows:

class FHF_Acl_AccessCheck extends Zend_Controller_Plugin_Abstract
    public function preDispatch(Zend_Controller_Request_Abstract $request)
         * @author Raju Gautam
         * Check login session and throw some message for expiry
        $hasIdentity = Zend_Auth::getInstance()->hasIdentity();
        if(!$hasIdentity && $module != 'user' && $controller != 'user' && $action != 'login'){
            // set some message and login form

Where I have checked if the the Zend_Auth has null identity and show/load the login form with some message. But while setting the message first I tried:

$this->_helper->FlashMessenger->addMessage(array('error' => "Session expired, please login again !"));

But this did not worked, threw error message instead.

So I researched then found in one of the pages in the internet and found the following solution:

class FHF_Acl_AccessCheck extends Zend_Controller_Plugin_Abstract
    public function preDispatch(Zend_Controller_Request_Abstract $request)
         * @author Raju Gautam
         * Check login session and throw some message for expiry
        $hasIdentity = Zend_Auth::getInstance()->hasIdentity();
        if(!$hasIdentity && $module != 'user' && $controller != 'user' && $action != 'login'){
            $flashmessenger = Zend_Controller_Action_HelperBroker::getStaticHelper ( 'FlashMessenger' );
            $flashmessenger->addMessage (array('error' => 'Session Expired ! Please login again !'));

So if anyone wants to set the flash messages from outside of the action controllers, then you should use something like this using Zend_Controller_Action_HelperBroker class and its static helper getStaticHelper.

$flashmessenger = Zend_Controller_Action_HelperBroker::getStaticHelper ( 'FlashMessenger' );
$flashmessenger->addMessage (array('error' => 'Session Expired ! Please login again !'));

With this, you can get any plugin outside of the action controllers.

Hope this will help others struggling for the same.

Good luck!


Read More

Avoid login screen in phpmyadmin and auto login

phpMyAdmin is the mostly used web based PHP application for MySQL client. When we use it in the local systems, we always need to enter username and password to login. To avoid prompting the login screen you need to overwrite the existing settings with our own. phpMyAdmin lets us to overwrite the settings/configurations by using a file in the root of its directory.

A file is always delivered named in its root. You just need to rename it to and change the following line:

$cfg['Servers'][$i]['auth_type'] 	= 'cookie';


$cfg['Servers'][$i]['auth_type'] 	= 'config';

And add the following two lines:

$cfg['Servers'][$i]['user']         = 'root';
$cfg['Servers'][$i]['password']     = 'asdf#asdf'; // use here your MySQL password

Hope this helps someone who is willing to avoid login screen in phpMyAdmin.

Cheers !

Read More