Saturday, October 1, 2011

Document/Attachment Reader - Google


Hi,

In this post I will discuss about document reader I had to use in one of my project. The files that we upload, their contents can be easily viewed using this reader. This is a product of Google. This is how it looks like:


Code:

Implementation of the Google document reader is extremely simple. Here is what you need to acheive it.

Monday, September 26, 2011

Paypal - Add business logo to paypal check out page


Hi,

There can be scenarios where you need to show the business logo in the Paypal checkout page.

This is how it would look like:




Code

Well this can be easily achieved by adding the following hidden field in your paypal form:

Tuesday, August 30, 2011

Drupal - Simple captcha


Hi,


This article is about using custom captcha in Drupal. This one is a custom created module in Drupal. This is developed under Drupal 6.20 environment. I am sure if you get a feel of it you can modify it for other versions as well.

You can get the code from here.

This is how it would look like:


Code & Explanation:

After you have downloaded the module. Install it in your project. Once done that, all you have to do is to put the following lines of code in your page form:

Friday, August 26, 2011

Remove special characters - PHP


Hi,

I know there are a million ways to remove special characters but this is one of the better solutions which I came across over the internet. Here is the PHP function:

function just_clean($string)
{
// Replace other special chars
$specialCharacters = array(
‘#’ => ”,
‘$’ => ”,
‘%’ => ”,
‘&’ => ”,
‘@’ => ”,
‘.’ => ”,
‘€’ => ”,
‘+’ => ”,
‘=’ => ”,
‘§’ => ”,
‘\\’ => ”,
‘/’ => ”,
);
while (list($character, $replacement) = each($specialCharacters)) {
$string = str_replace($character, '-' . $replacement . '-', $string);
}
$string = strtr($string,
"ÀÁÂÃÄÅ? áâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ",
"AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn"
);
// Remove all remaining other unknown characters
$string = preg_replace('/[^a-zA-Z0-9\-]/', ' ', $string);
$string = preg_replace('/^[\-]+/', '', $string);
$string = preg_replace('/[\-]+$/', '', $string);
$string = preg_replace('/[\-]{2,}/', ' ', $string);
return $string;
}

Best of luck

Thursday, August 11, 2011

Reading disabled HTML fields on page submit


Hi folks,

This probably is not a very big solution, but might be useful for newbies. To prevent users from entering data in any textbox or dropdown, you can either use "readonly" or "disabled". Readonly works fine, apart from the fact that the interface of the fields won't look like they are uneditable. Apart from that if it works for you, then its fine.

For "disabled"  option, not only the entire fields becomes uneditable, but also the interface has the feel that it is disabled. The biggest problem with disabled fields is if the form is submitted, the disabled fields are not submitted.


If you face a scenario where you absolutely have to use disabled fields and yet post the values in form submit, then a quick fix would be

Friday, July 8, 2011

Changing Drupal(6.2) theme on the fly

Hi,

This probably will be among my shortest post. The most commonly used module in Drupal for handling theme's is the ThemeKey module. But if you face a requirement where you have to change the theme of the page on the fly, then this post will be helpful.

To change the theme on the fly, you just need to write two lines of code i.e.

global $custom_theme;
$custom_theme="my_theme_name";

That's it. That is all that you have to do to change the page theme in Drupal.


Explanation:

Thursday, June 30, 2011

Google Map with custom draggable pointer


Hi,

I have been planning to upload this from a long time, but made it finally now. This possibly is one of my favorite codes to make life easy for programmers. In this, by using a single function you can perform various tasks in a google map. Tasks such as multiple pointers in one map, change the look and feel of pointers, drag and drop pointers and fetch their new coordinates etc.

I have compiled all this functionality in one function in a .php file, "gmap.php". With very slight alterations you can achieve any of the above functionality.

Before going to the details of how to use the function, here is how my web page looks like:


In my application, what I have done is, I have compiled all the various possibilities of my code in 1 web page for better understanding. Now before I start explaining it download the source code from here.

Code & Explanation:

First of you need to include the "gmap.php" file in your PHP page as:
<?php @include("gmap.php"); ?>

Now I am assuming you already have the latitude and longitude of the various points. If you just have the address without the latitude and longitude, check out my article of location to latitude/longitude conversion. The function that I am talking about takes just three parameters:

Tuesday, June 21, 2011

Save image in database(MySQL & Blob datatype)


Hi,

This is rather interesting topic, but is among the simpler one's. In this I will show how to save an image in its actual format in the database as data and fetching it as an image to the web page. First of all create a database table and assign "blob" data type to the fields that will hold the image. Here is the schema for the database table that I am using:

CREATE TABLE `employees` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`empname` VARCHAR(50) NULL DEFAULT NULL COLLATE 'latin1_general_ci',
`profile_pic` LONGBLOB NULL,
`ext` VARCHAR(5) NULL DEFAULT NULL COLLATE 'latin1_general_ci',
PRIMARY KEY (`id`)
)

[You can find the entire source code here]

Now that my table is ready lets move on to the HTML. It is a pretty simple one just a form with couple of fields as follows:

<form method="post" action="" enctype="multipart/form-data">
Enter Name:<br/><input type="text" name="emp_name" /><br/><br/>
Profile Pic:
<input type="file" name="pic" /><br/><br/>
<input type="submit" value="Save Image" />
</form>

The page looks something like:



After saving the data, this is what I get:


Code and Explanation:

When the form is submitted here is what I have done:


$content=file_get_contents($_FILES['pic']['tmp_name']);
$content=mysql_escape_string($content);

@list(, , $imtype, ) = getimagesize($_FILES['pic']['tmp_name']);

if ($imtype == 3){
$ext="png";
}elseif ($imtype == 2){
$ext="jpeg";
}elseif ($imtype == 1){
$ext="gif";
}

Tuesday, June 14, 2011

Google Rich Snippet


Hi,

In this I will be discussing about rich snippets, what they are and how can they be useful in SEO. One of my colleague was working on the same, and decided to share with me so I am posting it in. Rich snippets are simply few predefined attributes in HTML tags, which are treated in a special way by Google. Have a look at the following. This will make it simpler to understand what they are:



The above is screen shot from Google search results when I search by "yelp" keyword. In the above we see a star rating and total reviews received for that App. These information are not present in Google search results by default. To make this happen we need to use rich snippets. Rich snippets can be used to representing the following:

1. Reviews (as given above)
2. People
3. Product
4. Business
5. Recipe
6. Events

The rich snippets can be implemented in 3 ways:

1. Microdata
2. Microformat
3. RDF

Use(Code) & Explanation:

Tuesday, June 7, 2011

Simple javascript tooltip or help text


Hi,

In this post I will discuss of a custom made tooltip which you can implement in your HTML, without breaking a sweat. As usual, in this also, I am using jQuery as my Javascript framework. I have used the basic concept of generating lightbox to generate the tooltips. So lets see how it looks in the front end:

Before we go into the explanation you can download the source code from here.

Code and Explanation:

First let us see the basic HTML structure as:

<div style="float:left;margin-right:5px">This is text 1 </div><div class="tooltip">This is tooltip 1...</div><br/>
<div style="float:left;margin-right:5px">This is text 2 </div><div class="tooltip">This is tooltip 2...</div><br/>
<div style="float:left;margin-right:5px">This is text 3 </div><div class="tooltip">This is tooltip 3...</div><br/>
<div style="float:left;margin-right:5px">This is text 4 </div><div class="tooltip">This is tooltip 4...</div><br/>

Tuesday, May 31, 2011

Post in multiple Facebook fan page in one go


Hi,

This is yet another post related to Facebook API. In this I will be demonstrating how to make a wall post in multiple Facebook page of which you are an admin or a fan. A similar functionality I had posted in one of my previous post regarding posting in friends wall. In this also the basic idea is same. The main factor here is to generate the Facebook page list for the logged in user.

First we need yo understand the FQL(Facebook Query Language). Here we will be working with two tables, "page" and "page_admin". The page table is the master table and page_admin holds the mapping between Facebook user and the pages. Here is the query that I am using to fetch the list of pages:

$query="select page_id, name, pic_small, type from page where type<>'APPLICATION' and page_id in (select page_id from page_admin where uid =" . $uid . ")";

Here $uid is the Facebook user id of the currently logged in user. Also I have added a type<>'APPLICATION' in the where clause, so that I only get pages and not my applications. In Facebook, when you create a new App, it is also treated as a page. So I had to give the above validation.

Here is how the page looks:


Explanation:

Social sharing (Facebook - Twitter - Digg - Delicious)

Hi,

Facebook Share:

For sharing a page in Facebook, it provides a specific URL to share a particular page in facebook. The parameters that are passed are basically just an URL. What facebook does is, it parses the URL and fetches the meta title and description. Now these title and description are added as the title and description of the new Facebook post. For the image of the post, Facebook selects a random image from the page that is being shared. So when you are sharing a page, make sure it has proper title and description.

Here is an example of a sharing a particular page in Facebook:

<a href="http://www.facebook.com/sharer.php?u=<?php echo urlencode("URL_TO_SHARE"); ?>&t=TITLE_OF_POST">Share with Facebook</a>

Digg Share

Similar to Facebook, Digg also provides an URL to share a particular page. The URL of that page needs to be passed as parameter to Digg.

e.g.
<a href="http://digg.com/submit?url=<?php echo urlencode("URL_TO_SHARE"); ?>&title=TITLE_OF_POST">Digg</a>

Share Delicious

Saturday, May 21, 2011

Drupal force login/logout

Hi,

This is not a very regular scenario, but I had got one, where I had to make a user auto login when they are coming to my website via a newsletter, that I had sent to the website members. The flow is, first I create various email newsletters and distribute it among my website users by mailing them. The newsletters would contain a link back to my website. Now when the users click that link, they come back to my website. They have to enter few basic details such as the password, gender, date of birth etc. When they click next they get logged in to the website.

I am using Drupal 6.20 for this development. The users that I am talking about are basically drupal users as well, so I need to login them in Drupal framework as well. It is actually simpler than I had thought. In Drupal whenever a user logs in it creates a global variable, "$user", instead of session variables to store the details of the logged in users. So all I had to do is to overwrite that variable with the user details who needs to be logged in.

This is the code that I had used:

$user_details=db_fetch_array(db_query("select * from {users} where id=<USER_ID>"));


$user_details->hostname=$_SERVER['REMOTE_ADDR'];
$user_details->timestamp=time();
$user_details->roles=array('4'=>'client');


global $user;
$user=$user_details;

Explanation:

The idea is very simple. You just need to overwrite the $user variable with that in the database. So I simply fetch all the details of the user and put it in the $user variable. But just by doing this will not do the job, I also need to assign few extra variables such as the hostname, timestamp and roles. Hostname and timestamp are pretty much easy and self explanatory. What is vital is the roles variable given as:

Wednesday, May 18, 2011

Multiple database in Drupal


Hi,

Recently I have been working with a distributed database architecture in Drupal 6, without the use of multisite. So thought of sharing in the blog. Multiple database is very important in Drupal when you have custom tables along with Drupal inbuilt tables. The best practice is to keep separate database for both. For creating multiple database in Drupal, first you need to follow the conventional Drupal installation process. One's that is done, create a seperate database and dump all the custom tables in that database.

Assume the name of the drupal database is "drupal_db" and the name of the custom database is "business_db". Now after you have successfully completed installing Drupal in your server, go to sites/default/settings.php file. There you will find the following or similiar looking lines:

$db_url = 'mysqli://root@localhost/drupal_db';
$db_prefix = 'drp_';

1st step to convert the current Drupal setup into multi database, is to replace the above two lines with the following:


$db_url['default'] = 'mysqli://root@localhost/drupal_db';
$db_prefix['default'] = 'drp_';

$db_url['business_data'] = 'mysqli://root@localhost/business_db';

Basically you just need to create an array of connections. In this, $db_url['default'] refers to the default connection if you are not explicitly mentioning from which database the data needs to be fetched. Most cases this is the drupal database. For the custom database you need to create another index of the same array with the details of that database. In this case I have named it as "business_data" in:

$db_url['business_data'] = 'mysqli://root@localhost/business_db';

Now the main part is to switch connections as needed. For that I had used db_set_active() function. Generally I have used this switching process just before and after performing any database transaction. This function takes 1 parameter, which is the array index name which I had created earlier i.e. "default" and "business_data".

e.g.

Tuesday, May 17, 2011

SVG Charts - PHP

Hi folks,

In this post I will demonstrate possibly my first product in this blog. Generating charts has been a headache for many developers. This is a very simple package to generate interactive charts without the use of flash plugin. This uses basic concepts of SVG to generate those. Unfortunately explaining the entire class file will be a little out of scope of this blog, so I have prepared a short video explaining the functionalities of the chart, But again since this is custom made and just the first version, it may not look that great. But it would definitely serve some of your purpose.

This chart comes with a feature of downloading the chart in PNG format. You can go on fiddle with the main class file to customize the chart according to your needs. Here is the small video demonstrating the use of the chart:




Download: svg_charts.zip

Thursday, May 5, 2011

Facebook style quick friend search and select


Hi,

In this post, I will discuss how to create a friend selection widget as in Facebook. When ever you are inviting your friends, or sending some application request to your friend in Facebook, you might get a friend selection widget as below:


In this I have made a similar functionality using jQuery. Here is what my screen looks like:


In the above, as you start typing the name of your friend, the list below gets filtered quickly accordingly. This is not refreshing the page nor is calling any AJAX. The whole thing is in realtime. Also you can select/unselect 1 or more friend by clicking them. And finally when you click the "Send Request" button the form gets submitted with selected friends user id. This is how I have achieved this.

Code and Explanation:

First you need to download the entire source code from here. Now here is the basic HTML:

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:

Wednesday, March 30, 2011

Cricket score update - JSON

Hi

I probably should have got this script done long back. If you have a website or a blog where you want to integrate the score update for CWC 2011, then you just need to use the code given below. In this I am using an JSON API of json-cricket.appspot.com for fetching the details. All you have to is parse the JSON returned. The output will be as follows:


This API has not been tested thoroughly, but it surely returns. Here is the code:

For simple HTML

<html>

<head>
<title>Cricket Score Update</title>
</head>
<body>
<div id="score_board"></div>
<script type="text/javascript">
o={s:function(data){document.getElementById("score_board").innerHTML=data.match + "<br />" + data.score + "<br />" + data.summary;}};

Tuesday, March 29, 2011

Facebook style image collage

Hi,

In Facebook there are various applications which makes a collage of all your friends. The application may be showing your top followers, or friends who are in your same organization and so on. In this post I have created a  PHP script to do exactly the same. But for demo I have used a static array of users to create the collage image, which of course you can convert to a dynamic array fetching data from the database.

First lets see the output:


Everytime you refresh the sequence of users will get shuffled and the angle of rotation of the images are also randomly selected between -10 to +10 degrees. Few prerequisites before using the code is to copy a font file(.ttf) and paste it in the directory of the code. Rename the ttf file to "cfont.ttf". Secondly and most important is to enable you GD library if it is not enabled.

The code to get the above is:

<?php
$im=imagecreatetruecolor(300,300);
$white=imagecolorallocate($im,255,255,255);
$black = imagecolorallocate($im, 100, 100, 100);
imagefilledrectangle($im,0,0,800,500,$black);
$font = 'cfont.ttf';
$users=array();
$users[0]['image']="statham.jpg";$users[0]['name']="Jason Statham";
$users[1]['image']="antonio.jpg";$users[1]['name']="Antonio Benderas";
$users[2]['image']="will_smith.jpg";$users[2]['name']="Will Smith";
shuffle($users);
$marge_left=20;$marge_top=20;$i=0;
foreach($users as $key){
$i++;
$img_element=imagecreatefromjpeg($key['image']);
$angle=rand(-10,10);
$img_element = imagerotate($img_element, $angle , $black);
$text=$key['name'];
imagettftext($img_element, 10,0, 10, 20,$white, $font, $text);
imagecopy($im, $img_element, $marge_left, $marge_top, 0, 0, imagesx($img_element), imagesy($img_element));
$marge_left+=120;
if($i%2==0){
$marge_left=20;
$marge_top=$marge_top + 120;
}
}
header("content-type: image/jpeg");imagejpeg($im,null,100);

Explanation:

Monday, March 28, 2011

Rounded corners without CSS 3 - All browser compatible

Hi,

CSS 3 provides a wide range of design tweaks which change the entire attitude of the website. Most commonly used functionality is rounded corners to any element. In CSS 3 you can create rounded corners to any element. Apart from DIV's if you want to show some images with rounded corners or button, input boxes etc then also this javascript approach can be helpful, depending on your needs. The conventional CSS 3 approach is as follows:

-moz-border-radius:  5px;
-webkit-border-radius: 5px;
-khtml-border-radius: 5px;

But the problem is, few browser does not support it. So one way to achieve this is by using a jQuery plugin. For this you need jquery.corner.js and jquert.min.js. Click here to download the entire source code along with the required JS files.

This is the output you will get:


Explanation:

Sunday, March 27, 2011

Check if email has been read

Hi,

If you are working with newsletters, it is a part of the job to maintain a statistics, of the emails to which the newsletters are send. The statistics may contain, number of bounced mails, number of opened/unopened email and so on. In this post I will explain a method for checking whether an email has been read or not. For checking bounced emails, I hope I will add it as a seperate post.

The idea is very simple. When we are talking of whether an email has been read or not, we basically mean to say  whether the email has been opened or not. For achieving this, following is the technique I have been using in most of my projects.

Assuming we have the following table structure (this is the minimum columns needed, you can change according to your need):



First add a image tag in your email along with the other email contents, and do not mention any size of the image as:

<img src="....." />

The main trick is with the "src" attribute. In the src, instead of using an actual image, enter the path of a PHP file in your server with the full URL of the files as:

<img src="http://localhost/php/ismailopened/opened.php?id=1">

In "?id=1", the value 1 needs to be dynamic. It is the newsletter ID. Now in opened.php I have added the following code:


<?php
if(isset($_GET['id'])){

mysql_pconnect("localhost","root");
mysql_select_db("test");
mysql_query("update newsletter set isopened='1' where id=".$_GET['id']);

Friday, March 25, 2011

Crawling URLs - PHP

Hi,

In this post I will give the source code for crawling the various URL's of a particular webpage. The main things to keep in mind is pattern matching using preg_match() function. For achieving this first I am importing the entire page content of a web URL, and then I am parsing it to extract the various hyperlinks found in the page.

Now in this post I will just show the method of extracting the URL's. But you can implement this logic to do many tasks such as creating a search engine, which stores all the URL's found in a webpage along with it meta data, or you may also use this technique to create a sitemap for your website. More you think, more ways you may find to make this code into use.

So the code is:


<?php
function reqtime($url){
$start=microtime(true);
@file_get_contents($url);
$end=microtime(true);
return number_format($end-$start,2);
}

$body = file_get_contents("http://www.blogger.com/posts.g?blogID=3662517344220871310");
$out = array();
preg_match_all( "/(\<a.*?\>)/is", $body, $matches );
$count=0;
foreach( $matches[0] as $match )
{
$count++;
preg_match( "/href=(.*?)[\s|\>]/i", $match, $href );

if ( $href != null )
{
  $href = $href[1];
  $href = preg_replace( "/^\"/", "", $href );
  $href = preg_replace( "/\"$/", "", $href );

Thursday, March 24, 2011

Checking valid email domain - PHP

Hi,

Validating an email address is not a big deal. Conventionally we use two steps to validate an email address:

Step 1. Just use regular expressions to check whether an email address follows the correct pattern.
Step 2. Then you just send the an email to that email address with a activation link to make sure that the email is valid.

But you can do I more check in between Step 1 and 2, just to make things more sensible. Here is a small mockup code for doing that:

<?php


function validate_domain($email){
$strpos=strpos($email,"@");
$domain=substr($email,$strpos + 1);
if(!@file_get_contents("http://".$domain) && !@file_get_contents("https://".$domain)){
echo $email." Status: <font color='red'>Invalid email domain</font><br/>";
}else{
echo $email." Status: <font color='green'>Valid email domain</font></br>";
}
}

validate_domain("xyz@gmail.com");
validate_domain("xyz@incorrectdomainname.com");
?>


Explanation:

Multipart Email - PHP

Hi,

PHP provides a very simple mechanism for sending emails as compared to other scripting languages. But the problem with emails is, different email client work differently. What I mean to say is, there are many email clients which does not support HTML contents in email. What they do is, they just simply display the HTML tags, instead of parsing them. Now a good solution is to send the emails in plain format. Plain content type is supported by all email clients, irrespective of the fact that whether they support HTML or not.

But the problem with the format of Plain Content type emails, is you cannot create good looking email, with images and hyperlinks, as that will need a HTML content type. So the best solution is to format the email content is such a way that the email clients which support HTML email will show the emails in HTML format and the email client which does not support HTML will show the plain version of the HTML message.

For this you need to use multipart emails. It is very simple. You just need to create two version of the same email. One with the HTML tags and the other without the HTML tags. When you are done doing this, you need to keep few things in mind. Here is an example of multipart email:


<?php
$plain_message_text="This is a plain message:\n\nFor email clients, not supporting HTML\n\nhttp://php-drops.blogspot.com";
$html_message_text="This is a <b>HTML</b> message:<br/><br/>For email clients, supporting <i>HTML</i><br/><br/><a href='http://php-drops.blogspot.com' target='_blank'>PHP Drops</a>";

$notice = "This is a multi-part message in MIME format.";
$boundary = md5(time());

Wednesday, March 23, 2011

Get query execution time in PHP

Hi,

When you perform a Google search, it shows the approximate number of records and the time taken to make that search. e.g.


For a layman, that time may seem to be the time taken for the entire process. But actually its the time taken to generate the search results. So technically, its the time taken to execute the search query. I have used the following technique to do the same. But I am sure that can be many more ways to achieve it.

For this I created a simple table just for demonstration as follows:


Now my objective is to run a query on this table and fetch the time required to run that query using PHP. So this is the code that I have written:

Tuesday, March 22, 2011

Website Security - How to avoid using session variables for logged in users

Hi,

It is a very common practice of storing logged in user details such as username, first name, last name, user id etc in session variables. But even session variables can be vulnerable and easily hacked. I have come up with a strategy of storing user details in runtime without using session variables or cookies. You will find a sample source code at the end of the post.

The idea is very simple. Assuming I have a user table with the following schema and data:


Now when the user is logging in through login.php, first the data is validated with the above table. If user has entered correct credentials, instead of storing the user data in session variables, I am storing them in a separate log table as follows:


with the code:


$is_user=mysql_fetch_array(mysql_query("select * from users where username='".mysql_real_escape_string($_POST['username'])."' and password='".mysql_real_escape_string($_POST['password'])."'"));
if(empty($is_user)){
$message="Incorrect username or password";
}
if(!mysql_fetch_array(mysql_query("select * from user_log where sessid='".session_id()."'"))){
mysql_query("insert into user_log set userid=".$is_user['id'].",sessid='".session_id()."',dt='".date("Y-m-d",time())."'");
}


In the above, after user logs in the session id and the user details along with the current date is stored in the log table as above. In this case I am just storing the userid, but you can add more fields, such as first name, last name etc.

(note: I am not using any encryption for storing password, but it is highly recommended)

This was just half the job. Next is to check whether user is logged in or not. During this checking we will run a query to check whether there are any records with the current session ID. If a match is found the user is valid. This is done by:

Monday, March 21, 2011

Proportionate Text Zoomer - Javascript

Hi,

In this I have made a custom script which can be used in any website to increase or decrease the text size of the entire page. You can find the entire source code at the end of this post. The zoom in and zoom out functionality is performed irrespective of their current font size. e.g. if a span has font size 10 and h1 as 14, then this will make span to 11 and h1 to 15, based on a certain percentage.

This is what the sample page looks like:

In this script you can choose tags whose text needs to be increased/decreased. This is what you have to do in script.js to add a new tag to have the functionality:


  $(".increaseFont").click(function(){  // for increasing font

$('a').each(function(idx, item) {    //adding the funtionality to anchor tag
       size=parseInt(jQuery(this).css("font-size"));
  size++;
  jQuery(this).css("font-size",size + "px")
    });
})

Sunday, March 20, 2011

Cakephp Store procedure + multiple resultset fetch

Hi All,


I have been working on a project which involves huge data. So the idea is to use stored procedures to make the query execution fast. Most tricky part in this, is to fetch multiple-result set from a single store procedure. 


Step 1: Write the procedure which have the multiple select queries.
Step 2 : Make a component within your cake's controller folder(app/controllers/components) and paste the code given below:

function callstoreproc($procname,$paramarr=null)
{
$connstr = ConnectionManager::getInstance();

$conhost = $connstr->config->default["host"];
$conlogin = $connstr->config->default["login"];
$conpassword = $connstr->config->default["password"];
$condatabase = $connstr->config->default["database"];

$mysqli = new mysqli($conhost, $conlogin, $conpassword, $condatabase);

if (mysqli_connect_errno())
{
echo "Connect failed";exit();
}
 $query = $procname;
 if (mysqli_multi_query($mysqli, $query))
{
$i=0;
while (mysqli_more_results($mysqli))
{
if ($result = mysqli_store_result($mysqli))
{

AJAX + JSON

Hi,

JSON is a very lightweight script which is used to store data. It is useful because of its speed. Calling and working with JSON is much faster as compared to XML. This post deals with calling a JSON file via AJAX and parsing it accordingly.

To begin with we have the following json file, student.json with the following content:


{"students": [
        {"Name": "John Smith", "Age": "18", "Gender": "male"},
        {"Name": "Maratha", "Age": "19", "Gender": "female"},
        {"Name": "Rose", "Age": "17", "Gender": "female"},
    ]}

This of course is a sample data which I created manually. Now to call this file via ajax I will be using jQuery. Now I create a new file example.php and make a ajax call to the above "student.json" as follows:


jQuery(document).ready(function(){
jQuery.ajax({
type:"GET",
url: "student.json",
success: function(content){
.............
}
})
})

In the above example I am calling the json file after the entire page has been loaded in the browser. After the ajax call successfully executes, this is what I am doing:


success: function(content){
var students_json=eval("("+content+")");
total_students=students_json.students.length;
for(i=0;i<total_students;i++){
jQuery("body").append("Name: " + students_json.students[i].Name+ "  Age: "+students_json.students[i].Age+"  Gender: "+students_json.students[i].Gender+"<br>");
}
}

"eval()" function is used to convert a string into a JSON script. Next "students" is the name of the main root element. I am first finding the content length of "student", later I am executing a loop and extracting 1 field at a time and displaying the values in the web page. This is the output I get:

Friday, March 18, 2011

Website Security - How storing important information in cookie can be easily hacked

Hi,

This again adds to one of the security measures. Assuming you are storing some very vital information in your websites cookies e.g. transaction id in an e-commerce website.

It will take less than 10 seconds for any hacker to track down your cookies. All he has to do is to copy a code similar to this one:


javascript:alert(document.cookie.split(';').join('\n'))


go to your e-commerce website and paste it in the address bar and hit enter. As soon as he hits the enter button, immediately an alert box shows up listing all the cookies and PHP session id.


I created a simple example.php file with the following:



<?php
session_start();
setcookie("MY_COOKIE","this is the value of the cookie variable");
?>


then I executed example.php. The I copied and pasted "javascript:alert(document.cookie.split(';').join('\n'))" in the address bar and hit enter. This is what I got:



Apart from the above, every browser provides some way or the other to view the cookies and its values of a particular website. This is the fastest way to find out. This is useful for QA guys, while analyzing website.

Hope this helps.


Thursday, March 17, 2011

Object Oriented Javascript

Hi,

OOP is not just limited to PHP, you can implement its concepts to some extent in javascript as well. But before I move on with it in details, the most important thing you need to understand about OOP as fas as Javascript is concerned is the fact, that there are no classes as such, as we have conventionally known. Here the functions are treated as class, which may contain member functions and data members.

Here is the javascript

<script type="text/javascript">
function Person(name)
{
  this.name = name;
  this.getName = getName;
  this.setName = setName;
}
function getName()
{
  return this.name;
}  
function setName(name)
{
  this.name = name;
}
var personObj = new Person('Bob');

Facebook style hyperlinking - with/without javascript

Hi,

If you have seen facebooks hyperlinks, you will notice that most of the hyperlinks work using ajax calls. But what hackers love to do is to switch of javascript from the browser and try things. In case of facebook if javascript is enabled in the browser the page is called via ajax, but if javascript is disabled then also the hyperlinks do not stop working. What they do is instead of the ajax call, the page loads the conventional way i.e. simple href.

I have made a sample code for that, this is how it works. Its independent whether javascript is enabled or not. It works accordingly. Assuming javascript is enabled. The hyperlinks are as follows:


<a href="index.php?p=home.php">Home</a><br/>
<a href="index.php?p=page1.php">Page 1</a><br/>
<a href="index.php?p=page2.php">Page 2</a><br/>
<a href="index.php?p=page3.php">Page 3</a><br/>

Now I am loading a javascript which extracts the "href" parameter of all hyperlinks and stop the anchor tab to refresh the page by adding "return false" in the "onclick" event of the hyperlink as follows:


jQuery('a').click(function(){
link=jQuery(this).attr('href'); // extracts the value of the href attribute
.......
        .......
   return false;   // stops the page from refreshing on clicking the hyperlink
});



Now we parse the format of the 'link' variable and make a ajax call to load the destination page as: