Implement Non-Blocking Session in PHP

As we all know Session is the most important component in the web application. Before describing the non-blocking session, I would like too little introduce about PHP Session. The session is the way to store data for each user against a unique session ID. By default, session usages file to storing the session data. When session_start() is called then PHP creates a unique identifier number for that particular session. And sent that number to users browser to save that number. Contiguous create a new file with the same name of the unique identification number. And browser will use that unique identification number to communicate with that server. To know more about How Does PHP Session Works read this article.

Non-Blocking Session

What Does Session Locking:

When web server getting the concurrent request which involves with PHP Session. Then the first request will engage the Session file to work with it and locked that Session file. And rest of the request who also have to engage with Session, they will be blocked (waiting for the unlock of the Session file). When the first request did its activities then release the Session file and then the second request will engage with The session. And this happened until the last request is served. This is actually called Session Looking. To understand more about Session Locking read this article.

Non-Blocking Session:

To improve the application performance we need to avoid this problem. To avoid the PHP Session blocking we can start the session and then close the session. This will unlock the session file and allow the remaining requests to engage with Session, even before the previous request has served.

session_write_close(); function need to call to close the session.

This trick works great if you do not need to read anything in session while your another process is engaged with the session. With this technique, you still able to read the $_SESSION data while the session is engaged with another request.

Example Script:

// start the session
// read/write to session
$_SESSION['login_time'] = time();
// close the session
// now do my long-running code.
// still able to read from session, but not write
$twitterId = $_SESSION['userId'];

Search Key Value Pair in Multidimensional Array

Are you Looking for key value search of a multidimensional array? This script will help you to search multidimensional array by key value pair.

You will get following output after executing this script.


    [0] => Array
            [name] => DDD
            [role] => agent

    [1] => Array
            [name] => EEE
            [role] => agent


Create and download ZIP file in PHP

Here I am sharing a script for creating and download the ZIP file in PHP. Sometimes we need to create a zip file and download that file that script will helpful for that case.

Look at the above snippet, here you can see a function called createZipAndDownload() which takes $files,  $filesName, and  $zipFileName as a parameter. To use this pretty function, first of all, create an array with the file name. And then pass that files array as the first argument of createZipAndDownload(). The second argument with being directory path of these files and the third argument will be the name of zipping file.


// Files which need to be added into zip
$files = array('sample.php', 'sample.jpg', 'sample.pdf', 'sample.doc');
// Directory of files
$filesPath = '/ROOT/FILE_PATH';
// Name of creating zip file
$zipName = '';
echo createZipAndDownload($files, $filesPath, $zipName);



Terminate PHP Loop After a Certain Time

We all know every loop has a termination condition (conditions can be anything). And this code snippet is for terminating a while loop after a certain time. This is an actually funny script which is, increasing a value a certain time and then decreasing that value a certain time period.

From the above code snippet, you can see there is variable called $totalTime which carrying the total number of execution time (in second) for loop. Then $totalTime is divided into the two periods, and the first half is using to increasing the $counter value and the second half is using to decreasing that $counter value.


Terminating a PHP loop after a certain time preiod Raw


How Does PHP Session Works

Basically, the session is the system or way to store information for individual users. It’s storing individual users information against a unique session ID. So in this way, user’s data can be accessible across all pages of a website. PHP follow simple workflow for manage session, and that is when a session is started, then PHP either retrieve existing session or create a new session. If PHPSESSID is passed then PHP retrieved existing session otherwise creates a new session

By default, session creates a file in a temporary directory (which determined in php.ini file) on a server. All all the variables & value are stored there.

How Does PHP Session Works

How is Works:

  • Firstly PHP creates a unique identifier number (a random string of 32 hexadecimal number, e.g 3c7foj34c3jj973hjkop2fc937e3443) for an individual session.
  • PHPSESSID cookie passes that unique identification number to users’ browser to save that number.
  • A new file is created on the server with the same name of unique identification number with sess_ prefix (ie sess_3c7foj34c3jj973hjkop2fc937e3443.)
  • The browser sends that cookie to the server with each request.
  • If PHP gets that unique identification number from PHPSESSID cookie (on each request), then PHP searches in the temporary directory and compares that number to the file name. If both are the same, then it retrieves the existing session, otherwise it creates a new session for that user.

A session gets destroyed when the user closes the browser or leaves the site. The server also terminates the session after the predetermined period of session time expires. These are the simple mechanism steps that PHP is using to handle the session. I hope this article with help you to understand how PHP SESSION is working.

Understanding of PHP Traits

As we know PHP is a single inheritance language, so what does it mean? It means one class can only inherit from another one class. So it doesn’t allow to inheriting from multiple class. But sometimes it’s might be beneficial to inherit from multiple classes.

To take care of this problem PHP introduced Traits in their 5.4 release. With the using traits, the developer can avoid the problems of multiple inheritances.

What is Traits:

Traits are something like a group or bundle of methods which you want to use within other classes. PHP introduced traits to reduce code duplication and overcome the limitations of single inheritance.

Using PHP Traits

From the above code snippet, you can see we have traits called Common and two different classes called Article and Comments.
Both Article and Comments use Common traits. So when a class uses any traits then all of the methods will available within that class. So the socialSharing() method of Common traits is now available within of these two classes.

In this way, you can reduce your code and avoid multiple inheritances.

Return Image as response by PHP

Return Image as response By PHP

To return an image as a request response by PHP you fpassthru function of PHP. I have included a sample code snippet, which will help you to understand how to do this.

From the above code snippet, you can see I have opened an image with binary mode by fopen($image, rb). And then send that with appropriate headers by header(“Content-Type: image/png”). After that dumping that image by using fpassthru, and finally stop the execution of PHP. It’s really easy to return image as response by PHP

How to Install xDebug in Ubuntu

xDebug is most famous and popular PHP extension which provides the debugging of your code very smartly. It is most important to a programmer to debugging their code/data, xDebug gives us more flexibility to debug our code.  Here I am gonna show you how to install  xDebug in your ubuntu machine.

Run this code through your terminal.
[PHP]~$ sudo apt-get install php5-xdebug[/PHP]

Then open your php.ini file and add these code in your ini file.

# Added for xdebug
xdebug.remote_handler=dbgp xdebug.remote_mode=req
xdebug.remote_host= xdebug.remote_port=9000

Finally restart the server.
[PHP]~$ sudo service SERVER_NAME restart[/PHP]

All done! now you can enjoy your debugging.

Singleton Design Pattern

In software engineering, a singleton the design pattern which allowed only object of a class. That means singleton pattern restricts to create multi instance of a class. This is useful, when we need to create only one instance or object of a class. To do this we must need to ensure a mechanism where we can access that class without creating object for them.

This is very basic concept of  singleton design pattern.