30 December, 2010

Basic url rewrite example

URL that is readable looks nice. But despite efforts by developers, sometimes for instance, using a Content Management System (CMS) serve url's in the format like,


Now, this is really a bad url, and is prevelant with dynamic pages. Some of the problems of such url's are:
1) It exposes the type of data, query string to malicious users.
2) The characters such as question mark and ampersand can be troublesome.
3) Such url's wont be indedxed by search engines.

Solution to this is, above url can be mapped to something like this;


Looks much better. And in order to do such mapping, we need url rewriting.
Apache's mod_rewrite gives us the ability to rewrite urls. Url rewrite can be
done to redirect from old to new address, clean up dirty url's, as mentioned above.
This makes our url's search engine friendly which means search engines can index such urls.

For url rewrite, we create a file .htaccess at the root of our project, and add following line.

RewriteEngine On

Basic Redirects

Lets say we moved all of our files from an older location to a new one, now we want to redirect all the links to current location. For that we can do the following.

RewriteEngine On
RewriteRule ^old\.html$ new.html

What the above rule does, is, it simple redirect from old.html to new.html page.
The ^ sign indicates Start of the url to be matched. If this character is removed, then our rule would also match hold.html
The $ sign indicates end of the string to be matched. In this case users would not know a redirect has occured from old.html to new.html

But lets say you want users to know that redirect has occured, that means you want to force a redirect. In such case you can do as,

RewriteEngine On
RewriteRule ^old\.html$ new.html [R]

Using Regular Expressions in Url Rewrite
The full strength of mod_rewrite can be felt at expense of complexity. Using regular expressions for url rewrite, you can have rules for set or urls, and have redirection for all to actual pages.
For example,


Now, we can rewrite this kind or url to make it friendly, as,

RewriteEngine On
RewriteRule ^book/([0-9][0-9])/$ list_book.php?bookId=$1

So above rule will create urls such as, http://www.testthis.com/book/8

But if a user types in like, http://www.testthis.com/book/8, our url rewrite rule wont work, as the slash at the end is missing, so to prevent such problems, we can do as,

RewriteEngine On
RewriteRule ^book/([0-9][0-9])/$ book/$1/ [R]
RewriteRule ^book/([0-9][0-9])/$ list_book.php?bookId=$1

Now, if a user enters something like book/12, our first rules comes in to add a slash at the end,then second
rule comes into play.

Regular expressions in url rewrite can be expanded by using modifiers, that allow you to match url with indefinite number of characters. Lets say, our url is like,

Our rule wont match this, as we have checked against two digits only, so we should use modifiers in this case.

RewriteEngine On
RewriteRule ^book/([0-9]+)$ book/$1/ [R]

+ indicates one or more of the preceeding characters or range.
* means 0 or more preceeding characters or range

So, above rule will match both book/1 and book/3000

In this way we can use mod_rewrite to rewrite url. These are just an introductory examples. There's a lot more way to move ahead in url rewriting and regular expressions. I hope this basic url rewrite post can be of some help to others.

27 December, 2010

Excel to Array in PHP

Customer's data can come from various sources, and making it easier for them to get the data into our system means we are increasing our customer's count. So, our code should support importing of data from different sources.
And one of the common sources can be Excel. So, we need to create an interface for customers so that they can load data from excel to our database.
Instead of spending hours entering data into forms, users can simply use tools such as excel to load data from excel using php.
In the following code, we load data from excel in php, read it and display the data back to the users. The displaying of data part can be replaced by inserting the loaded excel data to database to suit individual needs. And we are
using XML to do this.

Let's say we have a form "form.php" as:


Now after user adds an excel file and uploads it, following code "do_act.php" is executed,

$dataArr = array();
if($_FILES["excelFle"]["tmp_name"]) {
$xmlDom = DOMDocument::load($_FILES["excelFle"]["tmp_name"]);
$allRows = $xmlDom->getElementsByTagName('Row');
//loop through each of the row element
foreach($allRows as $row) {
$cells = $row->getElementsByTagName('Cell');
$rowData = array();
foreach($cells as $cell) {
$rowData []= $cell->nodeValue;
$dataArr []= $rowData;

//so now you can check for the array of data as:
echo "
echo "

Excel to Array in PHP

Customer's data can come from various sources, and making it easier for them to get the data into our system means we are increasing our customer's count. So, our code should support importing of data from different sources.
And one of the common sources can be Excel. So, we need to create an interface for customers so that they can load data from excel to our database.
Instead of spending hours entering data into forms, users can simply use tools such as excel to load data from excel using php.
In the following code, we load data from excel in php, read it and display the data back to the users. The displaying of data part can be replaced by inserting the loaded excel data to database to suit individual needs. And we are
using XML to do this.

Let's say we have a form "form.php" as:


Now after user adds an excel file and uploads it, following code "do_act.php" is executed,

$dataArr = array();
if($_FILES["excelFle"]["tmp_name"]) {
$xmlDom = DOMDocument::load($_FILES["excelFle"]["tmp_name"]);
$allRows = $xmlDom->getElementsByTagName('Row');
//loop through each of the row element
foreach($allRows as $row) {
$cells = $row->getElementsByTagName('Cell');
$rowData = array();
foreach($cells as $cell) {
$rowData []= $cell->nodeValue;
$dataArr []= $rowData;

//so now you can check for the array of data as:
echo "
echo "

22 December, 2010

Dynamic functions in CodeIgniter Model

Using dynamic function can be of great ease at times. Since i was developing some project on codeIgniter, i thought of giving it a try to create dynamic functions in codeigniter model. The following code is just a startup, if this works out good then will add more of the functions in it.
Functions can be created on the fly using PHP's magic method __call(). As per php.net this method is triggered when invoking methods that are not accessible in object context.
So, in codeIgniter as there are controllers, views and models. I thought of adding a model that would create dynamic functions, which can then be accessed by controllers.
The code snippet is just a test.
I created a Test_model.php file as:

class Test_model extends Model {
private $id = 0;
private $table;
private $fields = array();
function Test_model() {
//setup the tablename and field names
function set_up_table($table, $fields) {
$this->table = $table;
foreach($fields as $key) {
$this->fields[$key] = null;
//magic method to set and get
function __call($method, $args) {
if(preg_match("/set_(.*)/", $method, $exists)) {
if(array_key_exists($exists[1], $this->fields)) {
$this->fields[$exists[1]] = $args[0];
return true;
else if(preg_match("/get_(.*)/", $method, $exists)) {
if(array_key_exists($exists[1], $this->fields)) {
return $this->fields[$exists[1]];
return false;
//function to insert to database
function insert() {
$this->db->insert($this->table, $this->fields);
return $this->db->insert_id();


Now the controller part:

class Welcome extends Controller {

function Welcome() {

function index() {
//name of fields in book table
$fieldsArr = array( 'id', 'author','title', 'publisher' );
$tableName = "book";

$this->load->model("Test_model", "test");
$this->test->set_up_table($tableName, $fieldsArr);
$this->test->set_author("John Doe");
$this->test->set_title("Advanced PHP Web Development");
$bookId = $this->test->insert();


And thats it. The code in controller sets values for all the fields and then we call insert function created in our model. The main objective behind the code is to show how dynamic functions tend to ease out the process of coding.

Cross domain communication using jQuery

Due to some restrictions added by browsers, communication across cross domains is not possible by simple use of Ajax technology. It can be done though by adding a server-side script like PHP, and CURLing the other domain to get data and then passing it on to our javascript. But this method requires more code and is
not scalable.

A better way is to dynamically add script to the page, whose source points to the service url and get the response (data) in the script. This is what JSONP
(Javascript Object Notation with Padding) does.

JSON is a lightweight data exchange format for exchanging data between browser and server, and jQuery has a native support for JSONP calls beginning with version 1.2. We can load JSON data located at another domain specifying a JSONP callback.

This can be done as:

$.getJSON(domainurl+"&callback=?", function(response) {
alert("Username: " + response.username);

In above code jQuery replaces '?' after 'callback=' with a generated function name to call. And on complete the function name is removed.

Despite its ease of use for cross-domain comunication, JSONP has some drawbacks as well. Lets say, if the dynamic script addition does not work then nothing happens, we do not get any errors, it means there is no any error handling support in JSONP.

20 December, 2010

Parse XML using Javascript

It is quite easier to parse XML using Javascript. Most of the browsers have XML parsers for manipulating XML. But, prior to parsing the XML it must first be loaded to XML DOM object, which can then be accessed with Javascript. Since for some security reasons, browsers do not allow access across domains, both the page and the xml it is trying to load should be in same server.

Lets's say, we have an users.xml file like:



Step 1: Load the XML

function loadXML(xmlFile) {
if(window.XMLHttpRequest) {
xvar = new XMLHttpRequest();
else {
xvar = new ActiveXObject("Microsoft.XMLHTTP");
xvar.open("GET", xmlFile, false);
return xvar.responseXML;

OR, the XML can be loaded as string as well, like

function loadXMLString(xmlString) {
//here xmlString is the content of XML as string
if(window.DOMParser) {
parseIt = new DOMParser();
xDoc = parseIt.parseFromString(xmlString,"text/xml");
else {
xDoc = new ActiveXObject("Microsoft.XMLDOM");
xDoc.async = "false";
return xDoc;

There are some properties of DOM u.parentNode gives parent node of u, u.childNodes gives child nodes of u, u.attributes gives attributes nodes of u, u.nodeName gives name of u , u.nodeValue gives value of u
And we have a nodeType Property
Element has NodeType 1, Attribute 2, Text 3, Comment 8 and Document 9

Step 2:
To get the length of nodes we can do as:

xDoc = loadXML("books.xml");
u = xDoc.getElementsByTagName("user").length;
//it will output 2

To loop through all the nodes we can do as:

xDoc = loadXML("books.xml");
u = xDoc.documentElement.childNodes;
var details = "";
for(var i = 0; i < u.length; i++) {
details +=u[i].nodeName+": "+x[i].childNodes[0].nodeValue+"

16 December, 2010

Detect Ajax request using PHP

Sometimes, we need to detect ajax request using php. In such case, we can write following code that checks whether the request is ajax or not. It is helpful in conditions such as when i have to load a page depending on condition using a same function in php.

echo "Ajax request";
else {
echo "Normal Page Load";

And thats it.

Check uncheck jquery plugin

I needed check all - uncheck all checkboxes feature to be added to lots of pages in one of my site, so thought of creating a jquery plugin for it, so that i would not have to write same piece of code here and there. So here's the plugin, if Check All checkbox is checked all the sub checkboxes are checked and vice-versa, and if Check All is checked and then any of the sub checkboxes is unchecked, then Check All will also be unchecked.

(function($) {
checkun: function(options) {
var defaults = {
chkAllName : "",
chkBoxName : ""
var options = $.extend(defaults, options);
var chkAll = options.chkAllName;
var chkBoxs = options.chkBoxName;
var chkBoxesLength = $("input[name='"+chkBoxs+"']").length;

$("input[name='"+chkAll+"']").click(function() {
//get checked state of chkAll checkbox
var chkState = $(this).attr("checked");
if(chkState) {
$("input[name='"+chkBoxs+"']").attr("checked", true);
else {
$("input[name='"+chkBoxs+"']").attr("checked", false);
$("input[name='"+chkBoxs+"']").click(function() {
var subChkState = $(this).attr("checked");
if(subChkState) {
//get the total checkboxes and total checked checkboxes
var chkedLen = $("input[name='"+chkBoxs+"']:checked").length;
if(chkedLen == chkBoxesLength) {
$("input[name='"+chkAll+"']").attr("checked", true);
else {
//uncheck the chkAll checkbox
$("input[name='"+chkAll+"']").attr("checked", false);

And to test it, we use the following

//load jquery.js

//  Check All

Thats it. Hope this helps someone.

11 December, 2010

How to extract segment of video using FFMPEG

Once i had a situation where i had to extract a part (segment) of a video lets say from 3rd second to 8thd second. So after searching through FFMPEG documentation
i came to know how this could be done.
Following code snippet can be used to extract a segment of video.

$inputFile = "melt.mpg";
$outputFile = "melted.flv";
//-ss is the start time in HH:mm:ss
//-t is the end time in HH:mm:ss
system("path-to-ffmpeg/ffmpeg -i $inputFile -ss 00:00:03 -t 00:00:08 $outputFile");

And that's it.

How to get Lattitude and Longitude from Address using Google Maps

We can easily locate store using Goolge Maps Geocoder.
Google Maps uses REST method for accessing the services.

Our code uses cURL to locate stores using Google Maps API geocoder,
to query HTTP based geocoding API and SimpleXML to parse the
returned response. So, following code can be used to get the lattitude
and longitude of an address using google Maps Geocoder.

Lets start with the code using cURL for request. The cURL request
returns an XML in fact KML response on valid request.

$apiKey = "your_api_key_for_google_maps";
$address = "your_address";
$city = "your_city";
$state = "your_state_prefix";
$zip = "your_zip_code";

$url = "http://maps.google.com/maps/geo?output=xml&key=$apiKey&q=";
$query = $address.",".$city.",".$zip;
$url .= urlencode($query);

//initialize rhte curl object
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);

Now its time to parse the XML response using PHP's SimpleXML.

$xmlResponse = simplexml_load_string($response);

//check if the status code in response is 200, i.e. OK
if($xmlResponse->Response->Status->code == 200) {
foreach($xmlResponse->Response as $response) {
foreach($response->Placemark as $place) {
$latLngArr = explode(",", $place->Point->coordinates);
$lattitude = $latLngArr[0];
$longitude = $latLngArr[1];

In this way we can find lattitude and longitude of an address
using Google Maps geocoder feature.

How to display tabs in Google Maps Info Window

Google MAPS API have added lots of tab related features to its info windows.
We can use multiple tabs in one info windows, and this can be changed
using different GInfoWindow methods provided be the API.
So displaying tabs in Google Maps Info Window is really a simple task.

Following code snippet creates an info window with two tabs in it.

Lets first create a container for our map.

var oMap = new GMap2(document.getElementById("divMap"));

Now, check if our browser supports Google Maps

if(GBrowserIsCompatible()) {
var oMap = new GMap2(document.getElementById("divMap"));

Now lets initialize the map to a specific area, this can be done as:

//the setCenter function accepts two arguments, one is the point
//calculated from lattitude & longitude, and second is the
//zoom level
if(GBrowserIsCompatible()) {
var oMap = new GMap2(document.getElementById("divMap"));
oMap.setCenter(new GLatLng(82, -110), 3);

Now lets add controls to our map. Google Maps API provides different
control functions, but we will be adding just two of those.

if(GBrowserIsCompatible()) {
var oMap = new GMap2(document.getElementById("divMap"));
oMap.addControl(new GSmallMapControl());
oMap.addControl(new GMapTypeControl());
oMap.setCenter(new GLatLng(82, -110), 3);

Now lets add a marker in our map. Markers in Google Maps are
the simplest among provided overlays.

if(GBrowserIsCompatible()) {
var oMap = new GMap2(document.getElementById("divMap"));
oMap.addControl(new GSmallMapControl());
oMap.addControl(new GMapTypeControl());
oMap.setCenter(new GLatLng(82, -110), 3);

marker = new GMarker(new GLatLng(82, -110));

Lastly lets add a tabbed info window now.

if(GBrowserIsCompatible()) {
var oMap = new GMap2(document.getElementById("divMap"));
oMap.addControl(new GSmallMapControl());
oMap.addControl(new GMapTypeControl());
oMap.setCenter(new GLatLng(82, -110), 3);

marker = new GMarker(new GLatLng(82, -110));

var tabInfos = [
new GInfoWindowTab("First Tab", "Contents for first tab."),
new GInfoWindowTab("Second Tab", "Contents for second tab."),
new GInfoWindowTab("Third Tab", "Contents for third tab.")

marker.openInfoWindowTabsHtml(tabInfos, {
selectedTab: 1, //first tab will be selected
maxWidth: 320 //max width of info window
GEvent.addListener(marker, 'click', function () {

And that's it.

08 December, 2010

Get all files inside a directory using php

Listing of files inside a directory can be done simply using php.
Following function can be used to list all the files inside a directory.

function list_directory($dirpath) {
$files = array(); //files array
$dirs = array(); //directories array
$file_num = 0; //set number of files to 0
$dir_num = 0; //set number of directories to 0
//check if the path is a directory
if (is_dir($dirpath)) {
//create a handle for opening directory
$hndl = opendir($dirpath);
//start the loop
do {
//read the directory
$fle = readdir($hndl);
if ($fle !== FALSE && $fle != "." && $fle != "..") {
//check if its a directory or a file
if (is_dir("$dirpath/$fle")) $dirs[$dir_num++] = $fle;
else $files[$file_num++] = $fle;
} while($fle !== FALSE);
return array($dir_num, $file_num, $dirs, $files);

30 November, 2010

How to integrate Paypal Subscriptions using PHP

After lots of googling, i was on right track to integrate paypal subscriptions using php. So thought, this might be of some help to others as well. Here is how i integrated the paypal subscriptions in php.
Step 1: Create a paypal sandbox account from www.developer.paypal.com, if you dont have it else login to it.
Step 2: Create a test account (Preconfigured Account link) as a buyer.
Step 3: Verify the account if status says 'Unverified'.
Step 3: Create a test account (Preconfigured Account link) as a seller.
Step 4: Create a form for subscriptions payment in paypal as following code:
This is the form that is submitted to paypal (sandbox for test)

//cmd is _xclick-subscriptions for subscription

//amount is USD 300

//monthly; can use Y for annual subscription

//setting rm to 2 and using return will send the response as post values

You need not set any IPN path from your sandbox account, because adding "notify_url" to the form will override the account default settings.

Step 5: Now to the ipn.php page

$url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
$postdata = '';
foreach($_POST as $i => $v) {
$postdata .= $i.'='.urlencode($v).'&';
$postdata .= 'cmd=_notify-validate';
$web = parse_url($url);
if ($web['scheme'] == 'https') {
$web['port'] = 443;
$ssl = 'ssl://';
else {
$web['port'] = 80;
$ssl = '';
$fp = @fsockopen($ssl.$web['host'], $web['port'], $errnum, $errstr, 30);
if (!$fp) {
echo $errnum.': '.$errstr;
else {
fputs($fp, "POST ".$web['path']." HTTP/1.1\r\n");
fputs($fp, "Host: ".$web['host']."\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($postdata)."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $postdata . "\r\n\r\n");

while(!feof($fp)) {
$info[] = @fgets($fp, 1024);
$info = implode(',', $info);
if (eregi('VERIFIED', $info)) {
if(isset($_REQUEST["txn_type"]) && (strtolower($_REQUEST["txn_type"]) == "subscr_payment") || (strtolower($_REQUEST["txn_type"]) == "subscr_signup")) {
//update database, send notification or do whatever here
else {
//the subscription type can be something else
else {
//this is not valid payment
//so log some error here

And success and cancel page can be done easily.
And thats it, hope this helps someone.

28 November, 2010

Codeigniter Library for getting Gmail Contact List

Today i needed to get the gmail contact list for a project that i am doing in codeigniter. For this is thought of making a library, so that it can be used easily. So, here in the complete library class fr getting gmail contact list.

if (!defined('BASEPATH')) exit('No direct script access allowed');

class GmailContacts_lib {

var $FEED_URL = "http://www.google.com/m8/feeds/contacts/default/full";
var $LOGIN_URL = "https://www.google.com/accounts/ClientLogin";
var $username;
var $passwd;
var $postData = array();

function GmailContacts_lib($gUsername, $gPassword) {
//constructor function
$this->username = $gUsername;
$this->passwd = $gPassword;

function get_gmail_contacts() {
$emailLists = array();
//create an array for post data
$this->postData = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => $this->username,
"Passwd" => $this->passwd,
"service" => "cp",
"source" => "anything"
//initialize the curl object
$curl = curl_init($this->LOGIN_URL);
//set the curl options
$this->set_curl_options($curl, CURLOPT_POST, true);
$this->set_curl_options($curl, CURLOPT_POSTFIELDS, $this->postData);
$this->set_curl_options($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
$this->set_curl_options($curl, CURLOPT_SSL_VERIFYPEER, false);
$this->set_curl_options($curl, CURLOPT_RETURNTRANSFER, 1);

//following variable contains the responses
$response = curl_exec($curl);

//check if the user has logged in sucessfully
//and save auth key if logged in
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
if( !empty($auth)) {
$headers = array("Authorization: GoogleLogin auth=".$auth);

//make the request to google contacts feed with the auth key maximum contacts is 10000
$curl1 = curl_init($this->FEED_URL);

//passing the headers of auth key
$this->set_curl_options($curl1, CURLOPT_HTTPHEADER, $headers);
//return the result in a variable
$this->set_curl_options($curl1, CURLOPT_RETURNTRANSFER, 1);

//results response
$feed = curl_exec($curl1);
//parse the feed and return email list array
$emailLists = $this->parse_response($feed);
else {
$emailLists = array("Invalid Username/Password");
return $emailLists;

//function to set curl options
function set_curl_options($ch, $option, $value) {
//make the post TRUE
return curl_setopt($ch, $option, $value);

//function to parse response
public function parse_response($feed) {
$contacts = array();
$doc = new DOMDocument();

//load the XML response
//check the entry tag
$nodeList = $doc->getElementsByTagName( 'entry' );

foreach($nodeList as $node) {
//children of each entry tag
$entry_nodes = $node->childNodes;
$tempArray = array();

foreach($entry_nodes as $child) {
//get the tagname of the child
$domNodesName = $child->nodeName;
switch($domNodesName) {
case "title":
{ $tempArray['fullName'] = $child->nodeValue; }
case "gd:email":
if (strpos($child->getAttribute('rel'),'home')!==false)
} //end of switch for nodeNames
} //end of foreach for entry_nodes child nodes
if( !empty($tempArray['email_1'])) $contacts[$tempArray['email_1']] = $tempArray;
if( !empty($tempArray['email_2'])) $contacts[$tempArray['email_2']] = $tempArray;
if( !empty($tempArray['email_3'])) $contacts[$tempArray['email_3']] = $tempArray;
return $contacts;

And thats it. Hope this helps someone like me.

18 November, 2010

Subtract hours from date in php

One of my friend asked me how to subtract hours from date in php. The subtraction
could be hours or days. So here is what i did for him, to subtract hours from date
in php.
Lets say we need to subtract two hours from current date, then

//get today's date
$today = date("Y-m-d H:i:s", time());
$hours = 2;
//first convert today's date to timestamp, as
$strTodayDate = strtotime($today);
//now subtract hours from date
$subtractedTimeStr = strtotime("- $hours hours", $strTodayDate);
//now get the resulting date, i.e. date prior to 2 hours from today
$finalDate = date("Y-m-d H:i:s", $subtractedTimeStr);
echo $finalDate;

And thats it. To subtract days from date use days in place of hours in above code as:

$days = 2;
$subtractedTimeStr = strtotime("- $days days", $strTodayDate);

Similarly, to add days or hours to date we can do as:

$subtractedTimeStr = strtotime("+ $hours hours", $strTodayDate);
$subtractedTimeStr = strtotime("+ $days days", $strTodayDate);

Hope this helps someone.

Get changed field names from database using PHP & MySQL

Yesterday, i had a problem to get changed field value in mysql from database. MY problem was,lets say i have a field "user_name" in users table and have value "Sudhir" in it, after some updates the "user_name" field's value changed to "John", now i had to find such fields whose values has changed.
After some testing with the codes, i was able to get the field name and its changed value from database. So here's the code snippet:

//define an array of field names and values
$uniqId = "1"; // this can be the user id in database, whose values are changed
//array of field names and changed values, i.e. these fields contain values other than listed in this array
$fieldsArr = array(
"first_name" => $firstname,
"last_name" => $lastname,
"location" => $location,
"ip" => $ip
//call function to get list of changed fields in database
$changedFieldValueArr = getChangedFieldValue($uniqId, "user_details", $fieldsArr);

This is the function part. Connect to database, select database first.

function getChangedFieldValue($uniqId, $tableName, $fieldsArr) {
$changedValuesArr = array();
$sql = "SELECT id FROM ".$tableName;
$sql .=" WHERE ";
foreach($fieldsArr as $fieldName => $fieldValue) {
$subSql =$fieldName ." = "."'".$fieldValue."'";
$finalSql = $sql.$subSql;
$res = mysql_query($finalSql, $this->connection);
if(mysql_num_rows($res) < 1) {
$changedValuesArr[] = array("fieldname" => "'".$fieldName."'" , "changedFieldValue" => "'".$fieldValue."'");
//resulting field names for changed values are added to array
return $changedValuesArr;

And thats it. I hope this can be of some help to someone like me. The code can be customized to a greater extent depending on the need.

13 November, 2010

Jquery Ajax in CodeIgniter

The time I first started coding in codeIgniter, i had lots of confusions regarding
how to implemente ajax in codeigniter. I was using jquery for a project in codeIgniter,
and had a need to use jquery ajax in different sections of my project.
Since codeIgniter is MVC supportive open source framework, implementation of ajax in it is similar to usage of
ajax in other PHP MVC frameworks.
Here is how i started using ajax in codeigniter.
CodeIgniter has Model, Controller and Views (MVC).
So i started with a view file, user_notifications.php
//I had used jquery library for javascript,
//as this is one of the library I am confortable with
//include the jquery library script

function add_note() {
var note = $("#txtNote").val(); // this note value is from input type text with id as txtNote
if(note != "") {
//call the ajax function of jquery to post data to controller funcition
type: "POST",
url: "user/members/add_note",
data: "&userId="+userId+"&add_user_note="+note,
success: function(responseTxt) {
return false;
return false;
in the view file we might have

In above code we are posting data using jqurey ajax function to a url specified in "url" variable
base_url() in codeigniter returns site's base URL as defined in config.php file
"user" is the folder name
"members" is the name of controller we are posting data to and
"add_note" is the function name in members controller

Now lets create a controller, members.php inside user folder

function add_note() {
//get the post data
$user_id = $this->input->post("userId");
$note_add = $this->input->post("add_user_note");
//add this note to database or process like you want
//the return successful or error message or something else that you want to, like
echo "Note Added Successfully...!";

The last echo message will be displayed by alert inside success function, with the message
passed from controller function as return as responseText.
So in this way we can use ajax with codeigniter.

10 November, 2010

Regular expression examples in php

Regular expressions in php are a good way for validating against user inputs. Though
usage of regular expressions slow the execution, and are really slower as compared to
string functions, they can be quite fun to play with if known how to. Regex can be used in different programming languages but since i work with PHP, i use them using PHP.

At the beginning, regex seemed to be invincible to me, but as i got into details of
its usage and worked with test codes, i got more and more interested.
So here are some of the common validation examples that can be done using regular expressions in php.
Following mentioned are code for 5 simple regular expression examples for validation in php.

1: Regular expression to check for integer value excluding 0

$test = "123";
$result = 0;

$pattern = "(^([1-9]{1})(([0-9]{1,10}))?)$";
$result = (int) ereg($pattern, $test);
echo $result;

2: Regular expression to check for integer value including 0

$test = "1230";
$result = 0;
$pattern = "(^([0-9]{1})(([0-9]{1,10}))?)$";
$result = (int) ereg($pattern, $test);
echo $result;

3: Regular expression to check for integer value double or float, such as 1.23, 0.48, , 0.487 etc

$test = "123.23";
$result = 0;
$pattern = "^(([0-9]{1,9})(\\.)?)(([0-9]{0,1})([0-9]{0,1})(([0-9]{0,1})([0-9]{0,1})?))$";
$result = (int) ereg($pattern, $test);
echo $result;

4: Regular expression to check for string between 1 to 255 characters, no spaces
$test = "thisisatest";
$result = 0;
$pattern = "^([[:alnum:]]){1,255}$";
$result = ( ereg($pattern, $test);
echo $result;

5: Regular expression to check for valid email address
$test = "this@gmail.com";
$result = 0;
$pattern = '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+' . '@' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$';
$result = (int) ereg($pattern, $test);
echo $result;

Above mentioned are just few examples that i have mentioned in this post. There is a long way to go with regular expressions in php. I hope this post provide at least some info regarding usage of regular expressions with php.

09 November, 2010

How to expire a link using php

Once i got a problem of how to expire a link after it is clicked once using php. My situation was,
i had to send some confirmation link email to users, and when a user clicked the confirm link then
it should be set as expired, i mean, clicking on it for second time (more than once) should not
execute a function, i.e it should act as a dead link when clicked once.
So for this problem, i used hash trchnique of php.
Here is what i did to expire link that is clicked once.
Step 1:
I created a hash using some secret and email address of user, as:

$secret = "234234456jbkjkbkj2b34kj2b4";
//the secret can be defined somewhere in the file or same function
$emailAdd = "john@doe.com";
//create a hash from this
$ourhash = sha1($secret.$emailAdd);
//store this hash in database

This created a unique hash, since email addresses are unique
Step 2:
Add the hash that we created in Step 1 to the confirm link,
that is to be sent to email, as,

$emailBody = 'This is a test.......';
$emailBody = 'Please click Confirm to proceed..!';

Now the hash is appened to the confirm link in email message.
Strp 3:
In somefunction.php file, check the hash in the link with ours,
since we know the email address and hash, we can do as,

//get the stored hash for $userId from database
$ourHash = $hashFromDb;
//now check this with the hash in url
$hashFromUrl = $_GET["hash"];
if($ourHash == $hashFromUrl) {
//update database or do some actions here
//delete the hash
else {
echo "This link in not valid.";

And thats it. I have done this in my own way, this has to be cleaned and securified
more, i think. But i hope this helps someone like me to startup.

08 November, 2010

Check if email is opened using php

Yesterday i had a problem to check if email is opened by a user using php. After some google search,i came to know that, checking if our sent email is opened by a user can be done by some simple trick.
Though this idea might not be applicable for all the cases, but can be of some help. This can be helpful in tracking users for newsletter, campaigns, etc. So following is the code snippet to detect if email is opened using php.
Step 1:
insert a 1 pixel image in the body of email that you create, like

$emailBody = 'This is a test message.';
$emailBody .='';
$emailBody .='Please feel free to contact me..!';
//send email using mail() function of php

Step 2:
Create the file take_action_open.php and add following code

//get the userid from url of image source
$userId = $_GET["userid"];
//add code to insert this user to database
//or do something with it.
//this user has opened the email that you have sent.

And thats it. You can track opened emails using this method. As i already
said this method may not be applicable for all cases, since images can be
disabled by some mail services as well. So need to find some other solution
in such cases. However, i think this code might be of some help to someone
like me.

Get path of a file in PHP

Once i have to get location of a file using a single line of code in php. Here's how i did it.

$filePath = substr($_SERVER["SCRIPT_FILENAME"], 0, strrpos($_SERVER["SCRIPT_FILENAME"], "/"));
echo $filePath; // this gives the full file path

Hope it helps someone.

01 November, 2010

CSV to Multi-Dimensional Array in PHP

Once i needed to convert a csv file contents to a multi-dimensional array in php. Converting a csv to a multi-dimensional array
can be done by reading the file by using php's fopen function and then looping through to insert data to the array.
Following is a code snippet that is used to get csv to multi-dimensional array in php.
My csv file was in the format "name" "email_address" without any column names.

$formattedArr = array();
$filename = "test.csv";
//csv format was
//name test@this.com
//tester tester@mail.com
//sudhir sudhirconscious@gmail.com
if (($handle = fopen($filename, "r")) !== FALSE) {
$key = 0; // Set the array key.
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$count = count($data); //get the total keys in row
//insert data to our array
for ($i=0; $i < $count; $i++) {
$formattedArr[$key][$i] = $data[$i];
fclose($handle); //close file handle
//csv to multidimensional array in php
echo "
echo "
And thats it.

Get elements by class name in javascript

At times, i need function to get all the elements using class name in javascript. But since such function does not exist as in javascript, so i thought of creating a similar function that can be used to get elements by class name.
Here is the code snippet:

function getElementByClassName(strClassName) {
var eleNames = new Array();
var totalFrms = document.forms.length;
for(var i = 0; i < totalFrms; i++) {
var eleLen = document.forms[i].elements.length;
for(var j = 0; j < eleLen; j++) {
if(strClassName === document.forms[i].elements[j].className) {
return eleNames;
for(t = 0; t < eleNames.length; t++) {
Thats is. Hope this helps someone.

31 October, 2010

Get all month names between two dates in php

Yesterday i faced a problem regarding date manipulation in php. I had to get all month names between two dates, after some work around, i managed to make it work. I created a function "get_months" and passed two dates i.e. start date and end date to find list of months between the two dates.
Here's the function:

function get_months($date1, $date2) {
//convert dates to UNIX timestamp
$time1 = strtotime($date1);
$time2 = strtotime($date2);
$tmp = date('mY', $time2);

$months[] = array("month" => date('F', $time1), "year" => date('Y', $time1));

while($time1 < $time2) {
$time1 = strtotime(date('Y-m-d', $time1).' +1 month');
if(date('mY', $time1) != $tmp && ($time1 < $time2)) {
$months[] = array("month" => date('F', $time1), "year" => date('Y', $time1));
$months[] = array("month" => date('F', $time2), "year" => date('Y', $time2));
return $months; //returns array of month names with year

Thats it. I hope this helps someone like me.

20 October, 2010

Compare dates using PHP

Some times before, one of my friend asked me how to compare two dates using php. As he was a beginner and didnt have much knowledge regarding date and time functions in php, i did some kind of explanation to him.
We can use a php function strtotime in order to compare two dates in php. strtotime converts any date format description to Unix timestamp, and what we can do is convert, dates that are to be compared, to unix timestamp and perform a simple comparision.
Let's assume, we need to check if our registration has expired.

//first take today's date
$todaysDate = date("Y-m-d");

//get the expiration date, mat be from database or somewhere else
$expirationDate = "2010-12-06";

//now we convert both, today's date and expiration date to unix timestamp
$todaysDateStr = strtotime($todaysDate);
$expirationDateStr = strtotime($expirationDate);

//now simply compare the two variables
if($expirationDateStr > $todaysDateStr) {
echo "Your registration is valid!";
else {
echo "Your registration has expired!";

And that's it. The date format can be any like "-" or "/". Just convert it to unix timestamp and then compare the dates using php comparision operators.
I hope this helps someone.

12 October, 2010

How to check for numeric value using Javascript

We can use some simple function to check numeric value using javascript. The following is code snippet that checks if a value is numeric or not, returns false if not numeric else returns true.
Hope this helps someone.

//following function is used to check for a numeric value
function is_numeric(numVal) {
return (typeof(numVal) === "number" || typeof(numVal) === "string") && numVal != "" && !isNaN(numVal);
var testThis = "123";

//check as follows
//returns true

How to check for alphanumeric characters using javascript

Some times before, i was asked by one of my friend to check for alphanumeric characters using javascript. I did it for him using regular expressions.
Following is the code snippet for checking alphanumeric characters.

var testId = "1123ASD";
if((testId.search(/[^a-zA-Z0-9 ]/g)) {
else {
//you can enter characters like + - *^$%^$, etc to check it

I hope this helps someone like me.

08 October, 2010

How to remove al element from array using Javascript

Yesterday, I got into a problem of removing any element from any array in javascript. After some testing, found the solution, thats better for me at least. The following code uses combination of plain javascript and jquery to remove element from an array.
Here is the code.

var arr = ['1', '2', '3'];
var usrId = '2';
//remove an element
arr.splice($.inArray(usrId, arr), 1);


07 October, 2010

How to extend more than one class in php

Since multiple inheritance is not supported in php, we have to find a way to support it, so that we will be
able to extend more than one class at once. For this we can fake multiple inheritance in php using some
class and object functions provided by php.
I came across the problem where i had to extend more than once class using a single class, and for that
after some research came to a solution that can be used to make php support multiple inheritance, if i can say that.

//this is the Abatract class that implements fake multiple inheritance in php
//not allowed to create instance of this class
Abstract class MultipleExtension {

public $_this;
private $_extension = array(); //contains extended classes

//constructor function that passes $this to our private variable $_this
function __construct(){
$_this = $this;

//function to add the extended class objects
public function addExtension($obj) {

//overloading the members with getter function
public function __get($name) {
foreach($this->_extension as $ext) {
//check if the property defined as $name exists in the class $ext
return $ext->$name;

//member overloading using setter function
public function __set($name, $value) {
foreach($this->_extension as $ext) {
//check if the property $name exists in class $ext
//and if it does assign the value in $value to $name property of $ext class
if(isset($ext->$name)) {
$ext->$name = $value;

public function __call($method,$arguments) {
foreach($this->_extension as $ext) {
//check if function exists defined in method variable for the extended class
if(method_exists($ext,$method)) {
//call the user defined function with method and parameters
return call_user_func_array(array($ext, $method) ,$arguments);

And below is the implementation of above abstract class that supports multiple inheritance

//this is the first class that sets firstname of a user
class First {
private $_firstName;
public function setName($firstname){
$this->_firstName = $firstname;
public function getName(){
return $this->_firstName;
//this is the second class that sets location of a user
class Second {
private $_locationName;
public function setLocation($location){
$this->_locationName = $location;

public function getLocation(){
return $this->_locationName;
//this is a test class that extends multipleExtension class that fakes multiple inheritance
class Test extends MultipleExtension {
function __construct() {
//call the function that stores all the objects of classes as shown below
parent::addExtension(new First());
parent::addExtension(new Second());

public function __toString() {
return $this->getName().' located in: '.$this->getLocation();
//now create object of Test class and do as follows
$obj = new Test();
echo $obj;
//This will output Sudhir located in: Nepal.

27 September, 2010

How to remove non-ascii characters from string

There is a simple way to remove non-ascii characters from a string. This can be used to filter values from POST variables as well. Following line of code does the thing.

$string = "This is a test É";
//replace the non-ascii characters from string with nothing i.e. remove
echo $string;

23 September, 2010

Regular Expressions using Javascript

Sometimes regular expressions can be confusing, but they are great tools for matching a string against a character pattern. They are used for validation of user entry or changing the document content. You can replace a 40 line if/else code with just one line of regular expression. For starters, regular expressions can be fear striking but as you move on with the flow its keeps of getting more and more interesting.
Different languages support regular expressions and they are not as tough as they seem at first sight. Many languages support "find" ,"replace" and "search" feature in regular expressions.
So in this article i will be writing about regular expressions using javascript, to the point that I am also informed to.
Basic Syntax
Let's say you want to search for a string "rain" in a text. You can use two different formats for this.
First is using String Notation

var srchFor = /rain/; //do not use quotation marks
//Second is Object Constructor
var srchFor = new RegExp('rain');
//You can check this as follows:
var str = "When will it rain";

The expression can be checked using match(), test(), search() or exec() method, all of these are listed later.
Let's say now you want to match a word that starts with some string, in this case, 'rain', you can check this by:

var srchFor = /^rain/;
var srchFor = new RegExp('^rain');
//Or you want to match a word that has just some string and en, in this case, has only 'rain' in it:
var srchFor = /^rain$/;
var srchFor = new RegExp('^rain$');

Here, ^ and $ are starting and ending indicator respectively.
And if want to match a word that ends with some string, in this case 'rain', then

var srchFor = /rain$/;
//Case sensitivity can also be checked. Like,
//if you want to find a word that ends with 'rain' regardless of the case,
var srchFor = /rain$/i; //Here i refers to case-insensitive
var srchFor = new RegExp('rain$', 'i');

Lets, say we have string that have the word 'rain' several times, now if we want to match a word that is repeated several times, then we can add a global
parameter 'g', doing this will return the matches as array. Such as:

var srchFor = /rain/g; //g refers to global

By default regular expressions match patterns only in single-line strings, so if we want to have a match for multiline strings using regular expressions then 'm' can be used. Such as,

var srchFor = /rain/m; //This matches for rain in multiline

And the parameters can be used in conjunction as well, like,

var srchFor = /rain/igm; OR /rain/gim OR /rain/min; etc in any order

So the above pattern matches 'rain' in multiline,regardless of case and returns array.

Period Character (.)
The dot character means match anything. Such as, match a string that has r at beginning and n at end. Such as,

var srchFor = /r.n/;

The above pattern matches 'ran', 'rin', 'ron', or even r#n or r n, etc.
However you can limt your choices by using square brackets, like

var srchFor = /r[au]n/;

The above pattern matches 'ran' or 'run'.
Exclude you choice, such as match a string excluding some , such as if you want to exclude 'ran' from searcgh then, do the following,

var srchFor = /r[^a]n/;
//But the square brackets match only one character at a time,
//so if you want to match multiple characters then pipes can be used,
var srchFor = /r(^a|u|i|eig|e)/;

This matches 'run', 'rin', 'reigh' and 'ren' but does not match 'ran'.

Escaping Characters
Certain characters need to be escaped, such as: +, /, -, (, ), *, {, }, and ?
Such as /r.n/ matches ran, run, but /r\.n/ only matches "r.n".
Lets us say, you want to validate email address using regular expression, then do the following:

var srchFor = /^[\W]+(\.[\W]+)*@([\W]+\.)+[a-z]{2,7}$/i;

In above case,
\W is shortcut for [^a-zA-Z0-9_]; match characters that have a to Z characters or 0 to 9 and underscore.
+ means 1 or more times possible
* means 0 or more times possible
? means 0 or 1 times possible
{n} means n times possible
{n,m} means n to m times possible

var srchFor = /^[\W]+(\.[\W]+)*@([\W]+\.)+[a-z]{2,7}$/i;

/^[\W]+(\.[\W]+)* matches sudhi, or sudhi.test
then add @ symbol, then
([\W]+\.) matches oncemore, oncemore.co
then add dot (.),
[a-z]{2,7} means 2 to 7 times the a-z characters are possible.
Other shortcuts are
\d means [0-9] Only integers
\D means [^0-9] All characters but integers
\w means [a-zA-Z0-9_] All alphanumeric characters and the underscore
\W means [^a-zA-Z0-9_] All nonalphanumeric characters
\b means N/A Word boundary
\B means N/A Not word boundary
\s means [\t\n\r\f\v] All whitespace
\S means [^\t\n\r\f\v] No whitespace

Methods Using Regular Expressions
There are several methods that take regular expressions as parameters. The expression itself—
the things inside the slashes or the RegExp constructor—is called a pattern, as it matches what
you want to retrieve or test for.
• pattern.test(string): Returns true or false depending on whether it matches the string
• pattern.exec(string): Returns array on finding match
• string.match(pattern): Returns array of strings on finding match
• string.search(pattern): Matches the string and the pattern and returns the positions and returns -1 if not found
• string.replace(pattern, replaceString): Matches the string against the pattern and replaces every positive match with replaceString.
• string.split(pattern, limit): Matches the string against the pattern and splits it into array

So, Regular expressions only match characters; you cannot do calculations with them. And they are language independent.

22 September, 2010

Map Objects to Database in PHP

Data Mapper Pattern
Since code and database change occurs often during development stage, the separation between domain code and database tends to be beneficial, so that change
in one does not create a need to change the other. There exists a pattern using which we can map objects to database. One probable solution for this can be a
Data Mapper Pattern.
A general idea of the mapper pattern is that a class translates attributes (properties) and methods of domain code to database fields and vice-versa.
Data Mapper is responsible for routing information between domain code and database, creating new domain objects depending on information from database and
updating/deleting information from database depending on information from domain objects.
The mapping between object-oriented code and database can be done in different ways. It can be extracted from XML files, extracting from php array in the class
itself, or hand-coding the correlation in Data Mapper Class. This way implementation of mapping php objects to database is relatively simpler.
Let’s consider an analogy; we have a problem domain for storing user information. So we would generally have two classes; User and UserMapper. So applying the
Data Mapper Pattern we can handle the mapping of objects of User class with database tables and columns using UserMapper Class. For this case we could use an
XML configuration file implementation.
In following xml file, we have “user" as root element that contains a series of field elements as shown below:




Save the file as uers.xml
The 'name' elements are actually the physical database field name. The .... holds a method "getTitle" to extract attributes.
And .... element holds User method to use when populating the object values. Information regarding creating table structure can also be
added in the xml configuration file, such as type and size of the field. Such information can be particularyl userful when we are creating some kind of
packaged installation script. The information can be used to dynamically create SQL to create database tables. This users.xml file can be read and parsed using
PHP5's SimpleXML functions, like


This XML configuration file will be read by our UserMapper class which acts as Data Mapper in this case. Since Data Mapper Pattern is unobtrusive in nature,
the domain object (User class in this case) remains competely unaware to Data Mapper's (UserMapper Class in this case) existence and due to this reason all the
domain objects (methods) must provided public access to the Data Mapper. In following example, we have Users class, that have all protected attributes but
provides 'get' and 'set ' methods.
Following is our sample Users.php Class

class User {
protected $id;
protected $title;
public function setId($id) {
if (!$this->id) {
$this->id = $id;
//the following function is called whenever an undefined instance method is called
//name of missing method is passed as first parameter and method arguments as second parameter
public function __call($name, $args) {
if (preg_match("/^(get|set)(\w+)/", strtolower($name), $match)
&& $attribute = $this->validateAttribute($match[2])) {
if ("get" == $match[1]) {
return $this->$attribute;
} else {
$this->$attribute = $args[0];
} else {
throw new Exception(
"Undefined method User::".$name."()");
protected function validateAttribute($name) {
if (in_array(strtolower($name),
array_keys(get_class_vars(get_class($this))))) {
return strtolower($name);
public function fetch() {
return $this->title;

And following is our Data Mapper Class

class UserMapper {
protected $conn;
const INSERT_SQL = " insert into users (title, name) values (?, ?)";
const UPDATE_SQL = "update users set title = ?, name = ? where id = ? ";

public function __construct($conn) {
$this->conn = $conn;
foreach(simplexml_load_file("users.xml") as $field) {
$this->map[(string)$field->name] = $field;
public function save($user) {
$rs = $this->conn->execute(

if ($rs) {
$inserted = $this->findById($this->conn->Insert_ID());
//clean up database related fields in parameter instance
else {
throw new Exception("Error: ".$this->conn->errorMsg());
public function findById($id) {
$row = $this->conn->getRow("select * from users where id = ?"
if ($row) {
return $this->createUserFromRow($row);
else {
return false;
protected function createUserFromRow($row) {
$user = new User($this);
foreach($this->map as $field) {
$setproperties = (string)$field->presentor;
$value = $row[(string)$field->name];
if ($setproperties && $value) {
call_user_func(array($user, $setproperties), $value);
return $user;
public function add($title, $name) {
$user = new User;
return $user;
protected function insert($user) {
$rs = $this->conn->execute(
if ($rs) {
$inserted = $this->findById($this->conn->Insert_ID());
//clean up database related fields in parameter instance
if (method_exists($inserted,"setId")) {
else {
throw new Exception("DB Error: ".$this->conn->errorMsg());
public function save($user) {
if ($user->getId()) {
else {
protected function update($user) {
$binds = array();
foreach(array("title","name","id") as $fieldname) {
$field = $this->map[$fieldname];
$getproperties = (string)$field->access;
$binds[] = $user->$getproperties();
public function delete($user) {
"delete from users where id = ?"

So, in this way using Data Mapper Pattern, we can map php objects to database in a simple way.

20 September, 2010

Collapsible Menu using jQuery

Displaying all information at once to a user is not a good idea. Instead data can
be presented to user as chunks, if it can be said. A good example of displaying
only some data at a time collapsible list. In the following section, i am building
a show/hide list, a collapsible list using jquery.

We will be implementing a list items that contain child lists, and at the beginning
the child lists are hidden, and can be collapsible.

In following html, we can see that List Item 3 has content; so its child list elements
are hidden and mouse cursor changes to hand when hovered. I will explain each section
and then provide a complete working javascript code for collapsible list using jquery.

Select all the LI list items that have list children elements and add click event
handler. The click event handler checks if the target elment of event matches this.

$("li:has(ul)").click(function(event) {

When a parent list item in clicked the we check that if its children are hidden by
using jquery is() function.

if ($(this).children().is(':hidden')) {

If the children are hidden, then we show them using show() function, and if they are
already shown we make them hidden by using hide() function. So this makes the list
collapsible. Return false is done to avoid needless propagation.

return false;

Then we change the cursor to pointer and add a click handler to our outermost list

.css('cursor', 'pointer')

The last line makes sure that cursor for those li list items that do not have ul lists
will be default and no image will be added to those lists.

$('li:not(:has(ul))').css({cursor: 'default','list-style-image': 'none'});

So this completes our collapsible list using jquery. Furthermore, more css styles
can be added and more jquery features to make it look better.
Following section has complete code for implementation of collapsible menu in jquery.

//head tag start
//include jquery.js script
//script tag start
$(document).ready(function() {
$('li:has(ul)').click(function(event) {
if(this == event.target) {
if($(this).children().is(':hidden')) {
else {
return false;
.css('cursor', 'pointer')
$('li:not(:has(ul))').css({cursor: 'default','list-style-image': 'none'});
//script tag end
//head tag close

  • Item 1

  • Item 2

  • Item 3

    • Item 3.1

    • Item 3.2

      • Item 3.2.1

      • Item 3.2.2

      • Item 3.2.3

    • Item 3.3

19 September, 2010

JSON Basics

JSON is just Javascript. It is a wat to represent objects in Javascript. Using JSON does not involve working with Document Object Model (DOM). Below is a simple JSON format:
var jsnData = { "totals": [
{"location" : "First", "itemsSold" : 10, "bought": 40},
{location": "Second", "itemsSold" : 120, "bought" : 60},
{"location" : "Third", "itemsSold" : 20, "bought" : 40}
Now the above JSON data can be accessed as follows:
//Get total items sold for first location
var firstItemsSold = jsnData.totals[0].itemsSold,
var secondItemsSold = jsnData.totals[1].itemsSold;
var secondItemsSold = jsnData.totals[1].bought;

Accessing the json based server response as json format
//lets consider basic example
//code for xmlhttprequest
if(xhr.status == 200) {
var jsnData = eval( '(' + xhr.responseText + ')' );
JSON is a better way to send objects or arrays to a server. And for working with such data, server should use some JSON library.

PHP Comet basics

Despite improving the user experience, Ajax still uses the HTTP model, i.e. client sending request for some resource to server and server responding to this request from client. This is generally called "Pull" method/architecture.
However, Comet, the stuff this article is on, uses "Push" architecture. Lets consider ana analogy: in case of chat systems, server pushes data to client as and when necessary at some intervals, as a result of which, communication between the two (client/server) is fast. If, chat systems would have been built using "Pull" method, then the communication would suffer.
Comet pushes information to the client via HTTP streaming. Simply saying, HTTP streaming is a continuous connection with the server that pushes data out to client at certain intervals.
Lets consider some sample code:

//get time the file was modified on
$changed = filemtime("some_file.txt");
$lastChanged = $changed;

//clear the file stats; so that file operation results are cleared

//check if it has changed; runs infinitely just for a test; remove this in
//real cases
while(true) {

//sleep for 3 secs; can be set as appropriate to create a delay

//check the file modified time
$lastChanged = filemtime("some_file.txt");

//clear the file stats; so that file operation results are cleared

//check the times
if($changed != $lastChanged) {
$outData = date("d:i:s", $lastChanged);

//send the data across HTTP stream
$changed = $lastChanged;

Since Comet focuses more on traditional web application servers, it is preferrable to use a system specially designed for HTTP streaming.

Get age from birthdate using php the easiest way

Once i had a situation to get age of a user from his/her birthdate. After some testing, i managed to work it out. Following
code is used to get age from date. I hope this might help someone like me.

//date in mm/dd/yyyy format; or it can be in other formats as well
$birthDate = "08/14/1972";
//explode the date to get month, day and year
$birthDate = explode("/", $birthDate);
//get age from date or birthdate
$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[1], $birthDate[0], $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])):(date("Y")-$birthDate[2] - 1));
echo "Age is:".$age;

Get current page from Codeigniter pagination

Once i had a simple problem to get current page number from codeigniter pagination. After some checks, i managed to get it working by simple one line of code. I hope this will help someone like me.

//here: $this->uri->segment(n) is the segment value that you pass when initializing pagination
//and $config['per_page'] is number of pages to be displayed during pagination initialization in codeigniter
$currentPage = floor(($this->uri->segment(n)/$config['per_page']) + 1);
echo "Current Page:".$currentPage;

16 September, 2010

Search Flickr by username using REST

Searching flickr users by username can be done simply using REST services provided by flickr. Following is a beginning but complete
code that search for a username in flick using REST service of flickr.

//REST url for flickr
$url = "http://api.flickr.com/services/rest";
$data = array(
"username" => "sudhi",
"method" => "flickr.people.findByUsername",
"api_key" => "ur_api_key_here"
//this is the query string initialization
$q = http_build_query($data);
$finalUrl = $url."?".$q;
//initialize curl
$ch = curl_init($finalUrl);
//return the response as string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the curl
$result = curl_exec($ch);
//use simpleXml for parsing the xml response
$xmlStr = simplexml_load_string($result);
foreach($xmlStr->user as $people) {
$attrs = $user->attributes();
//ths $attrs contains user information
echo "
echo "

Create breadcrumb from array

Creating breadcrumbs can sometimes be really dificult. Breadcrumbs can be created from array in php using some simple code.
Following code can be used to create breadcrumbs from array, just a beginning though, and can be re-written further to make it
more flexible. Hope it helps someone like me.

$id = $_GET['id'];
if ( strlen( $id ) < 1 ) $id = "home";
//this array contains page lists, with id, title and parent page named as main in here
$pages = array(
'home' => array( 'id'=>"home", 'main'=>"my_home", 'title'=>"Home",
'url'=>"bcrumb.php?id=home" ),
'members' => array( 'id'=>"users", 'main'=>"home", 'title'=>"Members",
'url'=>"bcrumb.php?id=members" ),
'sudhir' => array( 'id'=>"jack", 'main'=>"users", 'title'=>"Sudhir",
'url'=>"bcrumb.php?id=sudhir" )
//function to create breadcrumb from array
function crumbs( $id, $pages ) {
$bCrumbList = array();
$pageid = $id;
while(strlen($pageid) > 0) {
$bCrumbList[] = $pageid;
$pageid = $pages[ $pageid ]['main'];
for($i = count( $bCrumbList ) - 1; $i >= 0; $i-- ) {
$page = $pages[$bCrumbList[$i]];
if ($i > 0) {
echo( " echo( $page['url'] );
echo( "\">" );
echo( $page['title'] );
if ( $i > 0 ) {
echo( "
| " );
echo "Crumbs:" .crumbs($id, $pages);
echo "
echo "Page:".$id;

Instead of using array, data can be loaded from xml file as well in order to create breadcrumbs, using the same function above.

08 September, 2010

Get only the path for a file

Sometimes it is required the get only the path that a file exists. In such cases following function could be of some help. I
hope this function helps someone like me

function getPath($path) {
if(substr($path, -1, 1) == '/') {
return $path;
else {
$pathArr = explode('/', $path);
$total = count($pathArr);
$end = $pathArr[$total - 1];
if(substr_count($end, '.') > 0) {
$finalPath = implode('/', $pathArr);
return $finalPath;

Load all class at once in php

Loading all the classes at once in php can be done by a simple code. If we have requirement to load lots of php classes
at once then this can be really boring. So in order to load all class at once in php we could write some code. Following
php code does the job.

function loadModules($dir) {
//create an array to hold the class names
$classes = array();
//usign DirectoryIterator class of php to get the handle of directory that contains the classes
$dh = new DirectoryIterator($dir);
//loop through each file
foreach($dh as $file) {
//check if the file is not a directory and ends with a .php extension
if($file->isDir() == 0 && preg_match("/[.]php$/", $file)) {
//include the class
$class = preg_replace("/[.]php$/","", $file);
$classes []= $class;
return $classes;

05 September, 2010

Integrating Videowhisper in CodeIgniter

Some times ago, i confronted a problem of integrating videowhisper with CodeIgniter. Searched through videowhisper forums but could not get exact solution, though i managed to do it using info regarding integration for plain php code.
I hope this might help someone like me.
Lets say we have a project folder named "test"
Step 1:
Add the "videowhisper_conference.swf" file in you root folder (project folder test) and its necessary folders like "uploads", "emoticons", etc. in the same folder

Step 2:
Copy the contents of "videowhisper_conference.php" into your view file, where you want to display the video.

Step 3:
Create function in your controller for each of the file, such as videologin for vc_login.php, videostatus for vc_status.php file. Do this for all the .php files that you require.

Step 4:
Add following code in you .htaccess file
RewriteCond %{QUERY_STRING} room_name(.*)

RewriteRule vc_login.php(.*) folder_name/controller_name/videologin/%1? [L]
RewriteRule vw_rooms.php(.*) folder_name/controller_name/videorooms/%1? [L]
RewriteRule vw_files.php(.*) folder_name/controller_name/videofiles/%1? [L]
RewriteRule vc_status.php(.*) folder_name/controller_name/videostatus/%1? [L]
and so on for all the files that you need.

You are done.
I've mentioned general steps in this case. You need to pass on the logged in user id and other required values accordingly.
Hope it helps.

25 August, 2010

Unset empty elements in Array

It is quite easier to unset empty element(s) in an array in php. Following code will do the work.

//this is a test array
$testArr = array(1 => "First", 2 => "", 3 => "Third", 4 => "", 5 =>"Fifth");
//loop through the array and remove empty elements
foreach($testArr as $key => $value) {
if(empty($value)) {
//view the array with empty elements removed

08 July, 2010

Integrating Zend with CodeIgniter

Last day, I had to integrate Zend Framework with Codeigniter. This came out to be quite easier then i thought. So here are the steps for integrating zend
framework with codeigniter.

Step 1: Copy the Zend folder from inside the library folder of Zend Framework

Setp 2: Create a folder inside your system, such as ../system/zf.

Step 3: Create a helper file like: zf_helper.php and place it into ../system/application/helpers/
Here is the code for zf_helper.php file

//For Linux OS
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . BASEPATH . '/zf/');
require_once 'Zend/Loader.php';

//For windows OS
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . str_replace('/', '\\', BASEPATH) . 'zf\\');
require_once ('Zend/Loader.php');

Step 4: Add this helper to your ../system/application/config/autoload.php file

$autoload['helper'] = array('url', 'form', 'date', 'zf'); //zf is the helper that we have added for zend framework integration

Step 5: Now you can use any modules of Zend Framework from CodeIgniter, like in a controller file

class SomeTest extends Controller {
//in some function
function someFunction() {
//load Zend Classes
$username = "someuser@gmail.com";
$password = "somepassword";
$gCalen = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($username, $password, $gCalen);
$gCalen = new Zend_Gdata_Calendar($client);
//and so on

Show this is how Integrating Zend with CodeIgniter works

06 July, 2010

Get Google Calendar Events using cURL

Once i needed to get all the google calendar events to my site, i.e. getting all the events that we added to google calendar to our custom calendar. After some reading, i found some helpful tips for doing this and here is the code. This is just a snippet. For logging in to gmail account please check my other post. The authentication token obtained after successful login is used in the following code.
So, what this code does is, it gets google calendar events using cURL. The code is simple. Just the retrieving of xml feed of google calendar events is done here, after this we can parse the xml and display all the events to our custom page after some formatting. Checkout the code.

$fAuth = "authentication-token-obtained-after-successful-login";
$arr_headers = array();
$arr_headers[] = "Host: www.google.com";
$arr_headers[] = "MIME-Version: 1.0";
$arr_headers[] = "Accept: text/xml";
$arr_headers[] = "Authorization: GoogleLogin auth=".$fAuth;
$arr_headers[] = "Content-type: application/atom+xml";
$arr_headers[] = "Cache-Control: no-cache";
$arr_headers[] = "Connection: Keep Alive \r\n";

$url = "http://www.google.com/calendar/feeds/emialadd%40gmail.com/private/full";
$ch = curl_init();

curl_setopt($ch, CURLOPT_REFERER, "http://google.com");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $arr_headers);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4b) Gecko/20040612 Mozilla Firebird/0.9");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$resFin = curl_exec($ch);
echo $resFin;

05 July, 2010

Accordion style show/hide divs using jQuery

This is just a start, but thought it might be of some help to others, so posted the code snippet. The code uses class for divs and anchor tags. This is a simple demo of accordion like tabs, but i've just done show and hide of divs using jQuery selectors.
When a link above a div is clicked, the div immediately below the anchor tag is displayed and all other divs are hidden.
Some animation can also be used in place of just show hide.If none of other divs are displayed as block then the current div is not closed. And by default first div is displayed when page is loaded.
Check out the following code snippet

$(document).ready(function() {
//display by default the first div content
$(".acc:first").css('display', 'block');
//attach click event to anchor tags
$(".atest").click(function() {
//check for the display block or none of the immediate div next to anchor tag
var displayStatus = $(this).next().css('display');
if(displayStatus == "block") {
var otherDivsStatus = $(".acc").not($(this).next()).css('display');
if(otherDivsStatus == "block") {
else {
//hide all the divs except for the current div
Just a test html, this can be changed as needed

First Block

This is first div

Second Block

This is second div

Third Block

This is third div


Check All - Uncheck All multiple checkboxes using jquery

Sometimes later, i had to check and/or uncheck multiple checkboxes having same name being displayed dynamically). I have one checkbox for Check/Uncheck All, and depending on that, i had to check or uncheck other checkboxes. And if any one of the checkboxes, besides main checkbox, was checked or unchecked, then i would have to check or uncheck the main checkbox as well.
The text i have writte here might seem little confusing than the original source code, but the main point is i had to check/uncheck multiple checkboxes at once. So here is the jquery code that i wrote for doing the same.

$(document).ready(function() {
//get count of checkboxes with the same name
var countBoxes = $("input[name='chkTest[]']").size();
//move through each checkbox
$("input[name='chkTest[]']").each(function() {
$(this).click(function() {
//get the state, checked or not, i.e. true or false
var state = $(this).attr("checked");
//get the length of checked checkboxes
var chkedLength = $("input[name='chkTest[]']:checked").length;
//make the checked or unchecked state
var chkAllState = (chkedLength == countBoxes) ? true : false;
//now apply the state to main checkbox
$("input[name='chkAll']").attr("checked", chkAllState);
//this code checks or unchecks all sub-checkboxes depending on checked state
$("input[name='chkAll']").click(function() {
var chkAllStatus = $(this).attr('checked');
$("input[name='chkTest[]']").attr("checked", chkAllStatus);

Same height sub-divs using jQuery

Previous day i had to make height of all the child divs same. Actually i had 3 divs, with different height according to dynamic content, inside a main div, but i needed to make of all those child divs same irrespective of the content they had. So, i figured it out using s simple jquery code.
This code actually checks for a div that has maximum height, and then applies that max height to all the divs that is contained inside the main div. Check out the following code snippet.

//include your jquery.js file here
$(document).ready(function() {
//make a new array for storing the heights temporarily
var heightArr = new Array();
//loop through each of the child divs of parent div,
//i've used class of div, but it can be replaced with id as well
$(".mainDiv").children().each(function() {
var divHeight = $(this).height();
//push the height to array
//this is a function to get maximum value from an array
Array.max = function(array) {
return Math.max.apply(Math, array);
var maxHeight = Array.max(heightArr);
//now apply the maxHeight to all the divs css
$(".mainDiv").children().each(function() {
$(this).css('height', maxHeight);

23 June, 2010

ucfirst in mysql

Its quite hard to convert first character of a string to capital in mysql. Same problem existed for me. I however managed to work it out using following sql query. This query is used to capitalize first letter of a string to upper case similar to ucfirst in php.

SELECT CONCAT(upper(substr("test this one.", 1, 1)),"", LOWER(SUBSTR("test this one.", 2, length("test this one."))));

In above query, the string "test this one." can be replaced by the field name while performing query in database.

14 June, 2010

Find if multi-dimensional array is empty

Checking for emptinessin quite simple using php. Following function can be used to check if a multidimensional array is empty or not.
The code loops through all the values in multi-dimensional array to check for empty values.

$food = array(
'fruits' => array('', '', ''),
'veggie' => array('', '', ''),
"test" => ""
//set the empty count to 0
$countEmpty = 0;
//set number of keys count to 0
$countKey = 0;
foreach($food as $key => $val) {
if(is_array($val)) {
//loop through each values inside
foreach($val as $key1 => $val1) {
$val = trim($val);
if(empty($val1)) {
//empty value-- increment the empty value count
//increment the key count
else {
$val = trim($val);
if(empty($val)) {
if($countKey == $countEmpty) {
echo "Array is empty..!";
else {
echo "Array contains".($countKey - $countEmpty)." value(s)";
echo "
echo "Keys:".$countKey."
echo "Empty:".$countEmpty;

28 May, 2010

Download file using curl

Following code sample is used to download file using curl. In this example we download image using curl and
save it to some file in our directory.

// URL to Download Image
$url = "http://www.someurl.com/images/image.jpg";
// Initialize a CURL session.
$ch = curl_init();
// Pass URL as parameter.
curl_setopt($ch, CURLOPT_URL, $url);
// Return contents.in a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Data is in binary format
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//open file in write mode
$file = fopen("somedir/somename.jpg", "w");
//filename that the transfered binary data is returned to
curl_setopt($ch, CURLOPT_FILE, $file);
//Grab the jpg and save the contents in the $data variable
$data = curl_exec($ch);
curl_close($ch); // close curl resource

27 May, 2010

Add Events to Yahoo Calendar Using cURL

We can add events to yahoo calendar using curl or sync our custom php calendar with yahoo calendar using curl.
Yahoo calendar events have various parameters that need to be added in curl request for adding events to yahoo.
I've listed out some of the event parameters that I have known in the following code.
The code first login to yahoo with curl and after successful login it adds events to yahoo calendar.

$serviceUrl = "http://calendar.yahoo.com/";
$authUrl = "http://login.yahoo.com/config/login?";
$userAgent = "YahooSeeker-Testing/v3.9 (compatible; Mozilla 4.0; MSIE 5.5; http://search.yahoo.com/)";
$referer = "http://my.yahoo.com";
$login = "your-yahoo-username";
$password = "your-yahoo-password";
$numPostData = 22;
$cookieFileJar = "cookie.txt";
$cookie = 0;
$postData = "login=$login&passwd=$password&.src=&.tries=5&.bypass=&.partner=&.md5=&.hash=&.intl=us&.tries=1&.challenge=ydKtXwwZarNeRMeAufKa56.oJqaO&.u=dmvmk8p231bpr&.yplus=&.emailCode=&pkg=&stepid=&.ev=&hasMsgr=0&.v=0&.chkP=N&.last=&.done=" . $serviceUrl;

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);

// Set the referrer
curl_setopt($ch, CURLOPT_REFERER, $referer);

// Set the authentication url
curl_setopt($ch, CURLOPT_URL, $authUrl);

// Set number of post fields
curl_setopt($ch, CURLOPT_POST, $numPostData);

//Set post data in key=value pair such as login=yourusername
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

//Set filename for storing cookie information
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFileJar);

//Set ffilename for checking the stored cookie information
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);

//Set option for cookie
curl_setopt($ch, CURLOPT_COOKIE, $cookie);

//set this to output the result as string and not output directly ot browser
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//set this value to 1 if you want to redirect to the url you provided as service url
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

//Set this option if you do not want to verify ssl
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

//set this option if you do not want to verify peer's certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

//now execute the curl
$res = curl_exec($ch);

//check if the username and password is valid
if ((preg_match("/invalid/i", $res)) || (preg_match("/not yet taken/i", $res))) {
echo "Invalid Login";
else {
//logged in successfully
//TITLE => Event title
//TYPE => Event Type (10 is for Appointment by default)
//ST => Start date format is YYYYMMDDTHHMMSS
//DUR => Total duration in HHMM format
//DESC => is event description
//in_loc => is event location

//other parameters that can be set are
//in_csz => city/state/zip value
//in_st => street name, can have comma in between names

$date = "20100527T130000";
$title = urlencode("Lunch with Bhupal at KFC");
$loc = urlencode("Kathmandu");
$desc = urlencode("Is test event");
//url for the yahoo calendar event along with event parameters
$url = "http://calendar.yahoo.com/?v=60&ST=". $date . "&TITLE=" . $title . "&VIEW=d&TYPE=10&DUR=0200&DESC=".$desc."&in_loc=".$loc;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFileJar);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
//get the crumb from the link
preg_match("/&.crumb=(.*)\"/", $response, $mah);

$crumbs = $mah[1];
//pass crumb value along with event parameters to yahoo caledar event url
$finalUrl = "http://calendar.yahoo.com/?v=60&ST=". $date . "&TITLE=" . $title . "&VIEW=d&TYPE=10&DUR=0200&DESC=".$desc."&in_loc=".$loc."&.crumb=".$crumbs;
curl_setopt($ch, CURLOPT_URL, $finalUrl);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFileJar);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$finalResponse = curl_exec($ch);
echo $finalResponse;