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.




CREATE TABLE IF NOT EXISTS `posts` (
`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,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
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.

json-posts.php

<?php
//database connection
$dbHost='localhost';
$dbUserName='root';
$dbPassWord='';
$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
$json=array();
while($row=mysql_fetch_array($result)){
$from=array('id'=>$row['user_id'],'name'=>$row['user_name']);
$post=array('post_id'=>$row['post_id'],'from'=>$from,'post'=>$row['post'],'time'=>$row['time']);
array_push($json,$post);
}

//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...

{
"posts":[
{
"post_id":"3",
"from":{
"id":"103",
"name":"AshokRaj"
},
"post":"Third Post. Third Post. Third Post.",
"time":"2011-10-18 08:37:53"
},
{
"post_id":"2",
"from":{
"id":"102",
"name":"MohanKumar"
},
"post":"Second Post. Second Post. Second Post.",
"time":"2011-10-18 08:37:23"
},
{
"post_id":"1",
"from":{
"id":"101",
"name":"ArunDavid"
},
"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.

<html>
<head>
<script language="javascript" src="jquery-1.4.4.min.js"></script>
<script>
$(document).ready(function(){
$.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+="<div>";
output+="<b>"+json.posts[i].from.name+"</b><br/>";
output+=json.posts[i].post+"<br/>";
output+="<small>posted on "+json.posts[i].time+"</small>";
output+="</div>";
}
$('#posts').html(output);
});
});
</script>
</head>
<body>
<div id="posts"></div>
</body>

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
$UTC_Time=date('Y-m-dTH:i:s+0000',strtotime($GMT_Timestamp));
//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="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></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("-");
valid_date.setYear(arrDateCode[0]);
valid_date.setMonth(arrDateCode[1]-1);
valid_date.setDate(arrDateCode[2]);
var arrTimeCode = strTimeCode.split(":");
valid_date.setHours(arrTimeCode[0]);
valid_date.setMinutes(arrTimeCode[1]);
valid_date.setSeconds(arrTimeCode[2]);
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);
if(sec_diff<60){
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";
}else{
return month[date.getMonth()]+" "+date.getDate()+", "+date.getFullYear();
}
return date;
}
$(document).ready(function(){
$('.unformattedtime').each(function(index) {
$(this).attr('alt',$(this).html());
$(this).attr('title',$(this).html());
$(this).html(toFormattedDate($(this).html()));
});
});
</script>

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,

application/config/config.php

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

to

$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,

parse_str($_SERVER['QUERY_STRING'],$_GET);

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

application/controllers/search.php

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

If your url is,

http://localhost/tinywall/search/result/?name=David&age=22

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.

php-info.php

<?php
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...

.htaccess


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

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

If your website url is in the root of the server like 'http://example.com/index.php/<something>'. To use this like 'http://example.com/<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
IP API : IPinfoDB.com JSON API
Map API : Google Chart API


About  IPInfoDB.com

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 IPInfoDB.com API in this tutorial, so register yourself for a FREEaccount.

Register at IPInfoDB.com 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.

realip_details.php



<?php
/**
* GetIpDetails
* Author : S.MohanKumar
* IP API from ipinfodb.com & Google Chart API
**/
$realIp='';
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();
//ipinfodb.com API Key
$ipinfodbApiKey='YOUR_FREE_API_KEY_FROM_IPINFODB.com';

// set URL and other appropriate options
$url="http://api.ipinfodb.com/v3/ip-city/?key=".$ipinfodbApiKey."&format=json&ip=".$realIp;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, false);

// grab URL and pass it to the browser
$ipDetails_json=curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

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

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

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

function drawRegionsMap() {
var data = new google.visualization.DataTable();
data.addRows(1);
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);
};
</script>
<div id='map_canvas' style="width:600px"></div>

<fieldset>
<legend><b>Ip Details </b></legend>
<?php
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
?>
</fieldset>



DOWNLOAD