Monday, October 31, 2011

Create Free SMS app using PHP, JSON API, cURL and txtWeb

The current period is SMS era. Where in just 140 character made twitter dominate the social media. We are used to have everything right now as "Short and Sweet".

Thursday, October 27, 2011

Android Getting Started Hello World Example

I hope this post will help everyone those who want to start with Android applications.

To develop Android applications you should have a Android SDK  to run the dveloped application through the Virtual Emulator and Eclipse to develop the application.

Thursday, October 20, 2011

Facebook, Twitter like JSON feeds with PHP, JavaScript, Ajax, jQuery,MySQL

When you go to Facebook or Twitter, The first thing you notice is that the page is loaded and within seconds the status feeds will be displayed. That is because the page is loaded first and after that it sends an ajax request to another page and gets back the feeds in the JSON format and display it using JavaScript & jQuery.

We will demonstrate this with a simple posts from mysql table using PHP and JavaScript...

1 ) Create a mysql database and table 'posts' with the following schema.

`post_id` int(5) NOT NULL AUTO_INCREMENT,
`user_id` int(5) NOT NULL,
`user_name` varchar(50) NOT NULL,
`post` varchar(500) NOT NULL,
PRIMARY KEY (`post_id`)

And insert some rows in the table 'posts'

2 ) create a php page 'json-posts.php' that fetches data from database and display it in the JSON format.


//database connection
$dbName = 'twinfo_demos';
$dbLinkConnection = mysql_connect($dbHost,$dbUserName,$dbPassWord) or die("Couldn't make connection.");
$dbSelected = mysql_select_db($dbName, $dbLinkConnection) or die("Couldn't select database");

//select posts from database
$query="select * from posts order by post_id desc";
$result=mysql_query($query) or die("couldn't select data from table");

//create json format text from posts

//display it to the user
header('Content-type: application/json');
echo "{"posts":".json_encode($json)."}";

The above code will fetch the data from database and gives it in the following JSON format...

"post":"Third Post. Third Post. Third Post.",
"time":"2011-10-18 08:37:53"
"post":"Second Post. Second Post. Second Post.",
"time":"2011-10-18 08:37:23"
"post":"First Post. First Post. First Post.",
"time":"2011-10-18 08:37:23"

3 ) create anothe page 'posts.php' to fetch the posts in JSON format and display it to the user. In that page add the following code to send the ajax request for json data using jquery and display the posts for the user.

<script language="javascript" src="jquery-1.4.4.min.js"></script>
$.getJSON('json-posts.php', function(json) {//to send a ajax request for json data
var output="";
for(var i=0;i<json.posts.length;i++){//for each posts in the json response
output+="<small>posted on "+json.posts[i].time+"</small>";
<div id="posts"></div>

This will display the json posts in user readable format and also useful for giving API to others through JSON. Make use of my previous post to display the time in friendly readable format.

Live Demo | Download Code

Monday, October 10, 2011

Facebook like friendly time with GMT and UTC using PHP & Javascript

Usually when we want to insert timestamps in a database. We will either put the column default as 'Current Timestamp' or insert the value 'date("Y-m-d H:i:s")' into that column. But both the methods will result in inserting only the server time in the database and visitors from all over the world will see the same server time in the website.

So it is good practice to insert only the GMT time in the database and while displaying, convert it into the user's local time zone and display to them.

1 ) To get the GMT time stamp of current time in PHP, use the following,

$GMT_Timestamp=gmdate("Y-m-d H:i:s", time());
//Insert '$GMT_Timestamp' in the timestamp column of the database

Insert the above value in the timestamp column of table in database. This will give same GMT time value irrespective of server location or client location.

2 ) When you fetch the data from database, display it in the UTC format to the client like the following code,

//Fetch '$GMT_Timestamp' from the database table
//Display '$UTC_Time' to client and use javascript to make it to local time and friendly text
echo "<span class='unformattedtime'>".$UTC_Time."</span>";

3 ) Add the following javascript code in the head part of the webpage to convert the UTC formatted text into local time and display it in friendly text format.

<script language="javascript" src=""></script>
<script language="javascript">
function getValidDate(ivDate){
var arrDateTime = ivDate.split("T");
var strTimeCode = arrDateTime[1].substring(0,arrDateTime[1].indexOf("+"));
var valid_date = new Date();
var arrDateCode = arrDateTime[0].split("-");
var arrTimeCode = strTimeCode.split(":");
return valid_date;
var month=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
function toFormattedDate(gmdate){
var date=getValidDate(gmdate);
var offset=parseInt(date.getTimezoneOffset());
var sec_diff = (((new Date()).getTime()+(offset*60*1000)-date.getTime())/1000);
var day_diff = Math.floor(sec_diff / 86400);
return "Just Now";
}else if(sec_diff<120){
return "1 minute ago";
}else if(sec_diff<3600){
return ""+Math.floor( sec_diff / 60 ) + " minutes ago";
}else if(sec_diff<7200){
return "1 hour ago";
}else if(sec_diff<86400){
return Math.floor( sec_diff / 3600 ) + " hours ago";
}else if(day_diff==1){
return "yesterday";
}else if(day_diff<7){
return day_diff + " days ago";
}else if(day_diff<31){
return Math.ceil( day_diff / 7 ) + " weeks ago";
return month[date.getMonth()]+" "+date.getDate()+", "+date.getFullYear();
return date;
$('.unformattedtime').each(function(index) {

The above code will replace all the UTC format text given inside a span with class 'unformattedtime' to the friendly text format as given below.

<span class='unformattedtime'>2011-10-08T08:43:48+0000</span>

will be converted to friendly time format like

<span class='unformattedtime'>21 minutes ago</span>

This method will be regardless of the server and the client location. The displayed time to the user will be calculated for their local time zone and be displayed. So visitors from all over the world will see the time according to their timezone.

Live Demo | Download Code

Saturday, October 8, 2011

Both sement based and query string(GETmethod) variables in url ofcodeigniter site

By default codeigniter doesn't support query string or get method variables, we can use only segment based url. To enable both segment base and query string (GET method) variables, you need to follow the upcoming steps...

1 ) In yout codeigniter config file change the uri_protocol as specified bellow,


$config['uri_protocol']    = 'AUTO';


$config['uri_protocol']    = 'PATH_INFO';
//  OR

$config['uri_protocol']    = 'ORIG_PATH_INFO';

Some servers does not support 'PATH_INFO' as 'uri_protocol'. Then use 'ORIG_PATH_INFO'.

2 ) In your controller where you want to use query string variable, add the following line in the controller's constructor,


3 ) Now, you are able to use the query string variables in your methods of the controller like given below,


class Search extends CI_Controller{
function __construct(){
function result(){
echo "Search result for Name:".$_GET['name']." and Age:".$_GET['age'];

If your url is,


The above code prints,

Search result for Name:David and Age:22

Friday, October 7, 2011

Remove index.php from url of codeigniter site using htaccess

Usually when we run a CodeIgniter website, the url will have index.php after the hostname. To remove this we need to use mode_rewrite, htaccess.

First just check your php info of your server whether you have loded mod_rewrite module. To check this create  'php-info.php' file and put the following contents and run it.


echo phpinfo();

In your output, check whether in loaded modules 'mod_rewrite' is enabled or not.

If its enabled as given above, You are ready to use '.htaccess'. Otherwise you need to load the module in your server.

To remove 'index.php' from the url, create a '.htaccess' file ( no file name, just '.htaccess') in the root directory of your website where 'index.php' file of the codeigniter resides. And write the followin contents...


RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /$1

The above code is to rewrite the url 'http://localhost/<something>' to 'http://localhost/<something>' except for folders and files.

If your website url is in the root of the server like '<something>'. To use this like '<something>' , The htaccess code in the Line 4 should be like 'RewriteRule ^(.*)$ /index.php/$1'.

Find Real IP address and location details of visitor

Find Real IP address and location details of visitor

Finding real IP address of a user is becoming highly important now-a-days, that too if the visitor is behind any firewall it's getting as a tough task for the webmasters to trace the real ip address of the visitor. Mostly all the webmasters make use of Google Analytics to trace their visitors, where in the IP address is masked. So, here i come with a solution with the help of the following

Language : PHP with CURL
Map API : Google Chart API


IPInfoDB offer a wide range of free services based on our IP address geolocation database :

  • Web based IP geolocation lookup

  • IP geolocation API (XML, JSON and CSV format)

  • IP database updated monthly!

To find the IP address of the user you will need to make use of the API in this tutorial, so register yourself for a FREEaccount.

Register at to get the API Key

About Google Chart

Google Chart Tools provide a perfect way to visualize data on your website. We will be using Visualization: Geochart.


* GetIpDetails
* Author : S.MohanKumar
* IP API from & Google Chart API
function GetIpDetails($realIp){
//check if you have curl loaded
if(!function_exists("curl_init")) die("cURL extension is not installed");
// create a new cURL resource
$ch = curl_init();
// API Key

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, false);

// grab URL and pass it to the browser

// close cURL resource, and free up system resources

return $ipDetails_json;
$obj = json_decode($ipDetails_json);

function getRealIpAddress()
if (!empty($_SERVER['HTTP_CLIENT_IP']))
//check ip from share internet
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
//to check ip is pass from proxy
return $ip;

getRealIpAddress(); // display the real IP address
echo "<br/>";
$ipDetails_json =GetIpDetails($openIp);
$obj = json_decode($ipDetails_json);
<script type='text/javascript' src=''></script>
<script type='text/javascript'>
google.load('visualization', '1', {'packages': ['geochart']});

function drawRegionsMap() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('string', 'Title');
data.setValue(0, 0, '<?php print $obj->{'countryName'}; ?>');
data.setValue(0, 1, 'IP : <?php print $obj->{'ipAddress'}." ".$obj->{'cityName'}.",".$obj->{'regionName'}.",".$obj->{'countryName'}; ?>');

var options = {};

var container = document.getElementById('map_canvas');
var geochart = new google.visualization.GeoChart(container);
geochart.draw(data, options);
<div id='map_canvas' style="width:600px"></div>

<legend><b>Ip Details </b></legend>
echo "<b>IPaddress :</b> ".$obj->{'ipAddress'}."<br/>"; // IpAddress
echo "<b>Country name :</b> ".$obj->{'countryName'}."<br/>"; // countryName
echo "<b>State name :</b> ".$obj->{'regionName'}."<br/>"; // regionName
echo "<b>City name :</b> ".$obj->{'cityName'}."<br/>"; // cityName
echo "<b>Latitude :</b> ".$obj->{'latitude'}."<br/>"; // latitude
echo "<b>Longitude :</b> ".$obj->{'longitude'}."<br/>"; // longitude
echo "<b>Time zone :</b> ".$obj->{'timeZone'}."<br/>"; // timeZone