Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

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:

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

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

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

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");

Thursday, April 7, 2011

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:

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:

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: