Category Archives: Web Scripts & Programming

Automatic session timeout/logout using PHP after X Minutes of Inactivity/Idle time

PHP Automatic Session Expire after X Minutes of Inactivity/Idle time

 Automatic session timeout/logout using php


Session timeout is a notion and the only way you make you sure that no session ever will survive after X minutes of inactivity. Session timeout or Session expire depends on the server configuration or the relevant directives (session.gc_maxlifetime) in php.ini.


Typically the default is 1440 seconds(24 minutes), but you can alter the default to something else. Below are some Session configurations.


You can update this easily and without writing custom logic.


If your sessions are implemented with cookies (which they probably are), and if the clients are not malicious, you can set an time limit on the session duration by tweaking certain parameters. If you are using PHP’s default session handling with cookies, setting session.gc_maxlifetime along with session_set_cookie_params should work for you like this:


// server should keep session data for 1 hour
ini_set('session.gc_maxlifetime', 3600);

// each client remember their session id for exactly 1 hour

session_start(); // ready to go!


You can also put this in .htaccess file with a slight change in syntax.


php_value session.gc_maxlifetime 3600

php_value session.gc_probability 1

php_value session.gc_divisor 1


session.gc_probability, and session.gc_divisor directives: PHP has garbage collection it uses to clean up sessions that have expired, otherwise on a site with a lot of users accessing the site could cause a huge amount of session files to be continually generated. Garbage collection does not happen automatically and needs to be incorporated into your system maintenance routines.


You can also make a custom script that automatically logout a user if user is inactive (not performed any action or idle) for X minutes.


1) When user logged in, start session, start session expiry time, like this:

 $_SESSION['expire'] = time() + X*60; 

We took current time, added X minutes in it and stored this in session.


2) At every page check that if X minutes (for above script) have been passed or not make a file as include that in that page, like this:

If yes, clear session and logout, like this:

if(time() > $_SESSION['expire']){
    $_SESSION = array();


And then redirect to login page.


3) In else statement (if X minutes have not passed), reset time (takes current time and add X minutes in it and restore in session named ‘expire’) stored in session, like this:

else { $_SESSION['expire'] = time()+X*60; }


and do nothing – don’t clear sessions, don’t redirect to login page, so that user may stay at website, as much time as he is active.


You can also do this purely using JavaScript. Start an countdown timer. Then wait for activity and reset this timer. If there is no activity and timer goes off, you can call your logoff sequence.

/* Resets the timer. The timer is reset on events
   (mouse-move,mouse-click,key press,scrolling),
   these events occurs indicates that user is active on the application:

<body onmousemove="reset_interval()" onclick="reset_interval()" onkeypress="reset_interval()" onscroll="reset_interval()">

<script type="text/javascript">
//the interval 'timer' is set as soon as the page loads

var timer = setInterval(function(){ auto_logout() }, 20000);

// the figure '20000' (20 seconds) indicates how many milliseconds the timer be set to.

//e.g. if you want it to set 5 mins, calculate 5min= 5x60=300 sec => 300,000 milliseconds.
function reset_interval(){

    //first step: clear the existing timer
    //second step: implement the timer again
    timer = setInterval(function(){ auto_logout() }, 20000);
    //..completed the reset of the timer


function auto_logout(){

    //this function will redirect the user to the logout script
    if(confirm("You have been logged out from the application, Press OK to login again!")){



Hope it will works, let me know by your valuable comments if you need any more assistance.

Advantages: Let Google Host jQuery For Your Website

Most of us (Web Developer) use JQuery during the development, if you are not aware about the jQuery or interested in any other JavaScript Library then below is just a very quick overview about the jQuery.


jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.”


Well, how you include that in your file, generally as below.

<script type="text/javascript" src="/js/jQuery.1.8.x.min.js"></script>


We all know that the load of JavaScript directly affect the site page load time and Obviously on SEO. Then how to get rid by jQuery?
No worries, you know as usual Google always help us so let Google host jQuery for your website.


You can let Google AJAX Libraries CDN (content delivery network) serve jQuery directly from Google’s network as below.
There are three main benefits of doing this is Decreased latency, Increased parallelism and Better caching that directory affect you site page load.


You should use/include JQuery as below

<script src="//" type="text/javascript"></script>


Benefits of Google CDN Networks(Google hosted JavaScript Libraries)


Decreased Latency
A Content Delivery Network (CDN) distributes static content across various servers, diverse physical locations worldwide. When a user visits a page serving files from a CDN, their download will automatically target the closest available server in the network which can reduce download times.


Increased Parallelism
All browsers limit the number of connections that can be made simultaneously. Depending on which browser, this limit may be as low as two connections per hostname.
Using the Google AJAX Libraries CDN eliminates one request to your site, allowing more of your local content to be downloaded in parallel.


Better Caching
When a user visits a site, their browser will download static files so that when the user visits that page the files will not have to be downloaded again, saving bandwidth usage, server load.
Google AJAX Libraries CDN is that your users may not need to download jQuery at all.


If you’re curious why the <script> reference is missing the leading http:, It’s a trick which allows you to use a single reference that works on both HTTP and HTTPS pages.


“Protocol-less” URL is the best way to reference third party content that’s available via both HTTP and HTTPS.


Some logical interview questions & solutions

Below are some interview questions that usually asked during the technical interview if you are invited as a Sr. Developer.


These are very simple but it is always advice to read/learn and prepare yourself for interview.


These interview questions are just for checking your logic instead what you have done in your previous experience and how much strong you are in your programming language.


Hope these will help you a lot.


Questions are as below.

  1. How to get sum of diagonal elements of a symmetrical array using a single loop?
  2. How to check whether the string is palindrome or not?
  3. How to insert an element in linked list?
  4. Find the largest decreasing order array/series or sequence from a given array.


Try yourself once, if you need help scroll the page down 🙂


How to get sum of diagonal elements of a symmetrical array?
(Symmetrical array is an array that have same number of columns and rows)

$array = array(

echo "<pre>";
echo "</pre>";

echo "<br />";
echo "The array have ".count($array)." rows.";
echo "<br />";
echo "The array have ".count($array[0])." columns";
echo "<br />";
echo "The array have ".(count($array,COUNT_RECURSIVE) - count($array))." elements";
echo "<br />";

$sum_diagonal_element = 0;
for($i=0,$j=0; $i < count($array); $i++){
		$sum_diagonal_element += $array[$i][$j];
echo "<br />";
echo $sum_diagonal_element;

// -----
$sum_both_diagonal_element = 0;
$coloumns                  = count($array[0]);
$sum_common                = 0;

for($i=0,$j=0; $i < count($array); $i++){
	if($i == $j){
		$sum_both_diagonal_element += $array[$i][$j];
		if($j != $coloumns){ // skip the common elements
		$sum_both_diagonal_element += $array[$i][$coloumns];
echo "<br />";
echo $sum_both_diagonal_element;



How to check whether the string is palindrome or not?
(Palindrome means that it’s (string) reverse will remain same as it is)


$newstring = "";
for($i = strlen($string)-1; $i >= 0; $i--){
	$newstring .= $string[$i];

// It is better to change the case of string characters
if(strtolower($string) == strtolower($newstring)){
	echo "String is palindrome!";
	echo "String is not palindrome!";


How to insert an element in linked list?

class LinkedObject
    var $value;
    var $prev;
    var $next;

    public function __construct($value, $prev = null, $next = null)
        $this->value = $value;
        $this->prev  = $prev;
        $this->next  = $next;

    public function append(LinkedObject $insertee)
        $link = $this;
        while($link->next != null)
            $link = $link->next;

        $link->next = $insertee;
        $insertee->prev = $link;

    public function __toString()
        $str = $this->value;
        if($this->next != null)
            $str .= " » ";
            $str .= $this->next;
        return $str;

$head = new LinkedObject("foo");
$head->append(new LinkedObject("bar"));
$head->append(new LinkedObject("baz"));
$head->append(new LinkedObject("mahi"));
echo $head . "\n"; // output is "foo » bar » baz » mahi"


Find the largest decreasing order array/series or sequence from a given array.

$array = array(10,9,8,5,17,16,15,25,24,23,22,21,20,19,14,13,12,34,33,90);

$mycount 		= 0;
$arr_desc_order = array();

for($i=0; $i < count($array); $i++){

	if($i == 0){
			$arr_desc_order[$mycount][] = $array[$i];
		if($array[$i-1] < $array[$i]){
		$arr_desc_order[$mycount][]     = $array[$i];


// Find the array with maximun number of elements
$arr_elemt = $count= 0;
foreach($arr_desc_order as $arr){
	if(count($arr) > $arr_elemt){
	$arr_elemt = $count;

echo "<pre>";
echo "</pre>";


Hope the above will help you to crack the interview.
Best of luck!!

A Quick view on PHP magic methods

Magic Methods in PHP

(PHP Magical Reserved Functions Starts with double underscore)

According to me you all have heard about the PHP Magic methods.
You have also used some of these like __autoload and __construct.


Let’s have a quick view on magic methods, as sometimes it looks like it will hard to use these function but reality is these are very simple.
First of all let me tell what magic method is and why these are called magical? Are these methods really showed some type of magic as the name imply.


PHP reserves all function names starting with two underscore prefix (__) as magical.

Magic methods provide hooks into special PHP behavior.


PHP does not provide the definitions of the magic functions and the programmers have to write/code that what these functions will do. Magic functions will never directly be called by the programmer but PHP will call the function ‘behind the scenes’. That’s why they are called ‘magic’ functions because these can not be directly called and they allow the programmer to do some powerful things by the coding. I think it’s enough; you will be clearer by examples.


This is not a magic method exactly but it is very useful. The __autoload() function is automatically called when a class is instantiated and file will get include in the code. This is useful since you don’t always want to load every class again and again and add just in case you need it to add.


This magic methods is called when user create object (instances of your class) of the class. Usually this is used for creating constructor in php5.


As the name implies, the __destruct() method is called when the object is destroyed by PHP’s garbage collector. It accepts no arguments, and it is usually used to perform memory clean-up operations such as closing a database connection or closing any file.


class House{

  public function __construct() {
    $this->created = time();
    $this->logfile = fopen('/tmp/log.txt', 'w');

  public function __destruct() {
$home = new House;
echo $home->created;


This method is called when your object try attempt to read property or variable of the class which is unavailable or inaccessible.


This method called when object of your class attempts to set value of the property which is inaccessible or unavailable in your class.


This magic method trigger when you are attempting to call method or function of the class which is either inaccessible or unavailable.


This is same as __call executes when inaccessible or unavailable method in static context.


class House
    function __get($name)
        echo "__get executed as $name is unavailable";
    function __set($name , $value)
        echo "__set executed as $name not exists or inaccessible";
    function __call($name , $parameter)
        $a = print_r($parameter , true); //taking recursive array in string
        echo "__call executed with name $name , parameter $a";

    static function __callStatic($name , $parameter)
        $a = print_r($parameter , true); //taking recursive array in string
        echo "__callStatic executed with name $name , parameter $a";

$a = new House();
$a->abc = 3;//__set executed
$app =  $a->myvar;//__get triggerd
$a->getMyinfo('mahesh' , 'scriptarticle', 'blog');//__call willl executed
House::xyz('1' , 'sca' , 'help');//__callstatic will executed



This magic methods called when isset() function is applied on a property of the class which is inaccessible or unavailable.


This is just opposite of isset method as it called when unset() function called on inaccessible or unavailable property of the class.


class House
  function __isset($name)
      echo "__isset is called for $name is unavailable";
  function __unset($name)
      echo "__unset is called for $name";
$a = new House();



This method will trigger when you are going to serialize your class’s object.

This will execute when you are un-serializing any class object.


class House {
    public $name;
    public $width;
    public $data = array(); // stores misc. data in an array
    public $connection;     // holds some connection resource  

    public function  __sleep() {
        // list the properties to save
        return array('name', '56', 'data');

    public function  __wakeup() {
        // reconnect to the house


This executes when you are using echo on your object.

This will trigger when you are using object of your class as function.


class House
    public $myvar;

    public function __construct($myvar)
        $this->myvar = $myvar;

    public function __toString()
        return $this->myvar;

	public function __invoke($x)

$object = new House('Hello');
echo $object; // __toString will called
$object(8); // __invoke called


I have still left some magic methods as __clone(),__set_state() I’ll post a new article for these very soon.

Hope the above one helps you a lot.


what is difference between array_merge and array_combine in php

Difference between array_merge and array_combine in php


Array Merge

PHP: array_merge
Merge one or more arrays


Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one or if the arrays contain numeric keys, then the later value will not overwrite the original value and will be appended.


Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.


Have a look on example below


$array1 = array(“color” => “red”, 2, 4);
$array2 = array(“a”, “b”, “color” => “green”, “shape” => “trapezoid”, 4);
$result = array_merge($array1, $array2);


Output will:
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4


Array Combine

PHP: array_combine
Creates an array by using one array for keys and another for its values


$array1 = array(“green”,”red”,”yellow”);
$array2 = array(“avocado”, “apple”, “banana”);
$result = array_combine($array1, $array2);


Output will:
[green] => avocado
[red] => apple
[yellow] => banana


Search Engine Spider and User Agent Identification with “Ultimate User Agent Blacklist”

Search Engine Spider and User Agent Identification with “Ultimate User Agent Blacklist”


A user-agent is software (a software agent) that is acting on behalf of a user.
In many cases, a user-agent acts as a client in a network protocol used in communications within a client–server distributed computing system.


For more information view wiki


Automated Agents is called as Bots. has a complete list of all latest spiders/bots/user agents.
There are some more and those are anonymous (not known and have very different names).


If you develop a website and want to make the site accessible by some specific user agent or bots of a country, then you can update the information in your root .htaccess file.


As, Bot blocking blacklists are useless in some way as some rogue spiders just generate random user-agent strings so we will never have them in our list to start with, but We have tried list out as much as we can in the below zip file.


Ultimate User Agent Blacklist


What you have to done is, unzip the file and paste the code in your root .htaccess file, it will protect your website from unwanted crawling/indexing by anonymous bots.


If your website uses WordPress open-source, then can also use “Better WP Security” plug-in.
Just need to download and install the plug-in and go to “Better WP Security – Ban Users” Tab and enable “Enable Default Banned List”, you can also update the list according to your needs.


But please be careful before doing same, as it may affect your website’s core files and plug-in, So before doing this backup your website’s files and database.