Thursday, April 21, 2011

Posting to Facebook's friend wall - PHP


Hi,

This post is again a continuation of my previous posts related to Facebook Graph API. This one will sum up all the earlier post with a new functionality of posting to your own or friends wall. In this also I will be using the $facebook->api() to post in wall. Click here to download the entire source code.

My current page looks like:

In the above I have a form for updating my Facebook status. When I click the image of my friends a popup comes up and lets me post to that fiends wall as follows:



Code and explanation:

Tuesday, April 19, 2011

Get Facebook friend list - PHP


Hi,

This is the continuation of my previous post, were I explained how to create and work with Facebook session in your website. First you need to download the facebook.php class file. This is basically the back bone of Graph API. Click here to download the entire source code of this post. In this post I will be demonstrating how to get a list of all the friends in Facebook, along with their profile thumbnail, username, first/last name and profile ID.

Now Facebook provides an excellent API, known as FQL. This stands for Facebook Query Language. In FQL there are few predefined set of tables. All you have to do is to run simple SQL queries on those tables and fetch data. But since these are provided by Facebook, so we will not be using our conventional mysql_connect() etc to connect to the database. This is where the Graph API comes into play.

For running a FQL query this is what you need to write:


$fql    =   "YOUR_FQL_QUERY";
$param  =   array(
     'method'    => 'fql.query',
     'query'     => $fql,
     'callback'  => ''
);
$result_set   =   $facebook->api($param);


The $facebook->api() is the Graph API. $param array is defining the task that need to be performed, in this case it is a FQL query. Before getting into the explanation of this post, lets see how the page looks:


In the above I have listed all the friends thumbnails in <ul>, <li> form. When you click on any of the thumbnails. you are taken to its profile page.

Code & Explanation:

Sunday, April 17, 2011

Facebook login - FConnect Graph API (PHP)


Hi,

In this post I will be discussing about Graph API. The most basic use of it is when you want the users to register in your website via their Facebook profile. The advantage of doing that is, it saves all the email authentication, captcha etc validations. It simply fetches the users existing details from what is there in Facebook for that user. The use of Graph API is imense, which I hope to cover in my future post. In this I will be just concentrating on letting the users register in a website using the Graph API.

First and the most important thing, is to create your own App in Facebook. This is a very straight forward process, You just need to enter the App name, and URL. An App can be considered as the gateway between your website and Facebook's data. Follow this link to create a new App. Once you have set up your website you will be given a App ID and secret key. This will be needed in your code. So preserve this information carefully.

Now coming to the code. First click here to download the code. The main aspect of this code is the facebook.php file. This is the PHP SDK for Facebook Graph.

Explanation:

First you need to initialise the Facebook object by the App ID and secret key which you got in the above steps by:

$facebook = new Facebook(array('appId'  => 'YOUR_API_KEY','secret' => 'YOUR_SECRET_KEY','cookie' => true,));

Thursday, April 14, 2011

Parse CSV and enter in database


Hi,

CSV is one of the most convenient ways of importing and exporting data. CSV is nothing but a simple text files with fields seperated by ",". It can be edited by any spreadsheet editor, such that each cell is seperated by a ",". So if you want to parse a CSV file, you can do it by simply reading the file by fopen() of PHP, read each line, explode each line with a deliminator as ",".

But there is a simpler way to do that by using the PHP function, fgetcsv(). This reads 1 row at a time and returns the cell's in that row as an array. But before we start writing the code, the format of the CSV needs to be predetermined. That means the sequence of fields should be decided before starting the parsing.

Download the source code with the database. In my example I am maintaining the following table schema:

CREATE TABLE IF NOT EXISTS `csv_table` (
  `id` int(10) NOT NULL DEFAULT '0',
  `username` varchar(30) DEFAULT NULL,
  `phone` varchar(10) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
)


Before going into the code and explanation lets see the output of the code. This is the content of my CSV file:


Id,Username,Phone,Email
10021,John,22190097,john@mailinator.com
10022,Paul,556447885,paul@mailinator.com

The output of the above after executing my code is as:



In the above I am converting the CSV into table structure and storing in the database. 

Code and Explanation:

First I am reading the CSV file and traversing each line with the following code:

<?php
if (($handle = fopen("sample.csv", "r")) !== FALSE) {
$i=0;
while (($data = fgetcsv($handle, 0, ",")) !== FALSE)   // 0 specifies unlimited size of each row seperated by ","
{
                // code to manipulate with the CSV data
  }

}
?>

Now the code to create the table and updating the database is as:

Generate RSS Feed with PHP

Hi,

If you are looking for code to generate RSS via PHP, then I guess you already know what RSS is. So I am coming straight to the source code for generating it. In my example below, I am generating a RSS feed for the listing details of vaiours movies, which would contain, the movie name, image, description and a link to the details page of the particular movie.

I am keeping a database table for storing the details of the various movies. The table schema is as follows:

CREATE TABLE IF NOT EXISTS `rss` (
  `id` int(10) NOT NULL auto_increment,
  `movie_name` varchar(100) collate latin1_general_ci default NULL,
  `category` varchar(50) collate latin1_general_ci default NULL,
  `pic` varchar(50) collate latin1_general_ci default NULL,
  `link` varchar(100) collate latin1_general_ci default NULL,
  `description` varchar(300) collate latin1_general_ci default NULL,
  PRIMARY KEY  (`id`)
)

As you see in the above schema, I have categorized the various movies. This will make it more dynamic. Now before going into the actual code and its explanation, lets see how the RSS feed looks like:



Code & Explanation:

First I have created a simple .htaccess file, for URL rewriting. My idea was, user will have the category_name.xml as the URL and the list will come according the category name. Here is the htaccess:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)\.xml$ example.php?q=$1 [QSA,L]

In the above, all the url's ending with XML will be sent to example.php and the xml file name as the query string i.e. "?q="

Now coming to the code. The file example.php does all the hard work with the following:

First the database connection is build and the SQL query as:

<?php
mysql_connect("localhost","root");
mysql_select_db("test");

Wednesday, April 13, 2011

Javascript accordion (collapsible menu)


Hi,

In this post, I have created a custom accordion in simple javascript, with a little help from jQuery. But this is not a plugin, so it wont take up too much time to load in the browser. You can download the full source code here. Before going to the explanation, lets first see how it looks like:



The HTML structure that is there, I have done it completely using <ul> and <li>, this would make it easier to customize. Here is a sample HTML of the above:

<ul class="acc_options_ul">
<li class="acc_options"><h1 class="acc_options_title">Option 1</h1>  
<ul class="acc_op_content_ul">  
<li class="acc_op_content">  
content of the section.....  
</li>  
</ul>  
</li>
</ul>

The convention that needs to be followed is, the title of the each section of the accordion must be kept inside an <h1> inside the  <li class="acc_options"> tags. Each <li class="acc_options"> represents each section. You just need to include the style.css and accordion.js in your page and let the JS take care of the rest.

Explanation:


The functionality of the JS file is very simple. First when the page loads I am opening the first section of the accordion by default by the following:

Tuesday, April 12, 2011

Google Page Rank Calculation


Hi,
Page rank is an algorithm used by Google search engine, initially formulated by Sergery Grin and Larry Page. It is a algorithm which gives a rating to a particular web page. All the big companies are spending many dollars to increase their page rank. It may look daunting, but the page rank algorithm is in fact quit elegant and simple as follows:

PR(A) = (1-d) + d{ PR(T1)/C(T1)  + ...............+ PR(TN)/C(TN) }

PR(A) = page rank of page A.
PR(T1) = page rank of page T1 which links to page A.
C(T1) = number of outgoing links from page T1.
d = damping factor 0 < d < 1

Explanation:

Sunday, April 10, 2011

Custom radio button/checkbox - jQuery


Hi,

This can be considered as a continuiton of my previous post for creating custom dropdown using jQuery. In web 2.0 it becomes important to get rid of the conventional flat looking radio buttons and check box with stylish images but keeping their functionality. In this post I have made a custom solution for achieving that. Click here to download the entire source code.

I am using 2 pair of images. 1 pair for selected/unselected radio buttons and other checked/unchecked check boxes. First lets take a look how it looks:


Explanation:
First download the source code. All the trick is in the script.js file. You just need to follow few conventions given below for defining a radio button or a checkbox:

Radio button:
Conventionally this is what we write:

Saturday, April 9, 2011

Optimizing your page to come up in Google search

Hi,

This is a continuation of my previous post. In this I will be highlighting few generic rules making your web page appreciable to search engine. The search is basically performed on keywords. Such as "PHP Books", where PHP and Books are two different keyword. You need to architect your website in such a way that these two keywords in your page makes sense to Google.

Here are 10 ways how and where you will use those keywords and optimizing your web page:

1. In META keywords. Not necessary but a good practice. Keep them short and max till 255 characters

2. In META description. Keep the keywords towards the left, but forming a complete meaningful sentence.

3. In the page title. In extreme left, but not the first word.

4. In a H3 tag or higher. Use only once H1 tag in a page and multiple H2, H3 etc. as needed

5. In page URL. Do not duplicate the keywords in URL. Try to use .html or .htm in URL's to be on the safe side. You can use .htacces to convert your .php or .aspx files look like .html/.htm files.

Thursday, April 7, 2011

SEO Tip


Hi,

For a change I won't be submitting any source code in this post :), rather discuss a very favorite topic of mine, SEO. Search engine optimization is a very vast and a mystical thing. No one can teach you SEO, you need to find your own strategies. But there are always few basic basics, which I will be highlighting in this POST.
(All the points are in reference to Google search engine)

First why we need SEO?
Search engine optimization simply means building a website which can be found by various search engine, such that your website name shows up when a search is performed. If your website shows up in search results then your chances of bringing viewers to your site increases. Its a way to increase traffic to your site. And as we all know traffic is all we need for a websites success ;)

How do we put our website in search engines database?
Well this might not be such a difficult question to answer. Few basic steps you may take are:

1. Submit your URL to Google through http://www.google.co.in/addurl.html
2. Sitemaps:

Create a webmaster account for your website. For this you need to have a Gmail account. Login to that account and go to https://www.google.com/webmasters/tools/ and add your website. But the job is not done yet, now you need to create sitemap xml files for the various pages in your website, upload it to your server and submit the URL for that file in the webmaster tools. After you have done that, Google will start scanning those URL's and index them.

Check out my earlier post for creating sitemaps or you can also refer to sitemaps.org for the format of the sitemap XML's.
You can also create the sitemaps for your website, using www.xml-sitemaps.com

Google adsense working logic (advertisement impression tracking) - PHP


Hi,

In this post I will demonstrate how you can advertise on other website and keep track how many times the advertisement has been loaded in that website. This is again an example from GD library. For this I need a database to store the various images for advertisement. The database schema is as follows:

(Click here to download the entire source code with the full database)

1. Table for storing the various advertisement details

CREATE TABLE IF NOT EXISTS `advertisements` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`img` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

2. Table for keeping track of impressions
CREATE TABLE IF NOT EXISTS `adsense_track` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`ip` varchar(30) DEFAULT NULL,
`dt` datetime DEFAULT NULL,
`imgid` int(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

For you to advertise your image you need to supply a simple <img> to the external webpage or blog. In this it will look like:

<img src="http://localhost/php/adsense/advertisement.php?ad_id=1">

Now the source of the image is a PHP file with a parameter ad_id. Now in advertisement.php I have the following:

$ad_details=@mysql_fetch_array(mysql_query("select * from advertisements where id=".$_GET['ad_id']));
if(!empty($ad_details)){

 mysql_query("insert into adsense_track set ip='".$_SERVER['REMOTE_ADDR']."', dt='".date("Y-m-d H:i:s",time())."', imgid='".$_GET['ad_id']."'");
 $im=imagecreatefromjpeg($ad_details['img']);
 header("content-type: image/jpeg");
 imagejpeg($im,null,100);
}else{
 
 $im=imagecreatefromjpeg("noimage.jpg");
 header("content-type: image/jpeg");
 imagejpeg($im,null,100);
}


Explanation:

Wednesday, April 6, 2011

Tiny URL generating source code - PHP

Hi,

Tiny URL's are very popular when it comes to shortening a web URL. There are many third party tools such as bit.ly, tinyurl.com etc. But if you want to do it yourself, then you will find the entire source code and the logic of how it works in this post.

For this you need to keep in mind the following:
1. Providing an interface to the user to enter any URL and on submitting it a short URL is generated. The domain of the short URL will be in your server.
e.g.
if your website name is http://tiny.url, then the tiny urls should look something like, http://tiny.url/#####. Where "#####" is a tinyword which represent the actual URL which the user has entered.

2. You need to convert the above http://tiny.url/##### into its corresponding URL and redirect the page to there.

In my case instead of http://tiny.url/##### I will be using http://localhost/php/tinyurl/######, since I am running from my localhost. So lets start with the development.

Code and Explanation:

Monday, April 4, 2011

Creating widget with Javascript and PHP

Hi,

For those who do not know, a widget can be considered as a small section in your web page, whose content is being rendered from a different website. To understand this, google adsense is a very good example of a widget. In Adsense, you are provided with a javascript. All you need to do is to copy and paste the code in any part of your website to generate the advertisement. Now how the advertisement is getting generated, is not your concern.

But you need to configure the google adsense according to your need, e.g. the dimension of the adsense. After you are done with configuring it you are given a javascript code, as I mentioned above. Which you just need to copy and paste in your website or blog.

Click here to download the entire source code of the example given below, with full database.

So the basic things that we need to program for creating a widget is as:
1. A configuration section where the user will configure the widget, which may include color, title etc. as per your needs
2. Most importantly the embeddable code, which the end user will copy and paste after their configuration is done.

How ever there is one more thing needed from a programmers perspective, that is the content of the widget. The content of the widget is completely dependent on your business logic and the configuration data that the end users have set.

Example:

Sunday, April 3, 2011

Read Excel Sheet (.xls) file with PHP

Hi,

If you need to do large data migration from an excel sheet to your MySQL database, the most conventional way is to convert the .xls or .xlsx files to simple CSV(comma seperated file) and read it using PHP file read function. However we can also read a .xls file without converting it to a csv file. We can even navigate through the various worksheets in a single file. Click here to download the entire source code. I have used couple of external class files to achieve this.

Lets have a look at the spreadsheet I am using as example:

Code and Explanation:

Saturday, April 2, 2011

Rotate Image - PHP (GD Library Elaborated)

Hi,

GD library is such a strong architecture, that you can do anything using it. If you want to rotate a simple jpeg file using PHP, this is the code that is needed:


<?php
$im=imagecreatefromjpeg("img.jpg");
$white=imagecolorallocate($im,255,255,255);
$im=imagerotate($im,20,$white);

header("content-type: image/jpeg");
imagejpeg($im);

The image transformation from original to rotated image is as follows respectively:                                      
       


Explanation:

Friday, April 1, 2011

QR Code - PHP

Hi,
Quick Response code are getting really popular. It was introduced by Toyota. Its more commonly used in Japan. For those who are wondering what a QR Code is, this is how it looks like:


The above is the QR Code of "http://php-drops.blogspot.com/". It can contain website URLs, text or other data. It is similar to bar code, but more portable in various devices. The beauty of this is, all you need to decrypt the code is a smart phone with a camera. You need to have a reader in it. Take a picture of the above and you will get the details of the code in your mobile on the go. Here is a video I found in Youtube which demo's how to use it: