Friday, September 28, 2012

PHP Currency Converter with Google Currency Converter API


Are you looking for a reliable PHP Currency Converter, here is Google give you a solution from their open Google Currency Converter API


How this API Works:


This PHP Currency Converter work with following URL call back.



Querying Converter API from PHP function as per following URL:


q=1USD=?INR

http://www.google.com/ig/calculator?q=1USD=?INR

Based on Google Currency Converter API, I build an PHP Function to get Currency values from the out put of http://www.google.com/ig/calculator?hl=en&q=1USD=?INR. as PHP Array
function google_currency_converter($amount,$to,$from="INR")
{
 $content = file_get_contents("http://www.google.com/ig/calculator?hl=en&q=$amount."."$from=?$to"); 
 // Remove Spaces on API Output
 $content = preg_replace('/[^A-Za-z0-9.]+/','',$content);
 // Match All Currency values 0-9 and .(decimal)
 preg_match_all('/([0-9.]+)/', $content, $m);
 
 // Convert values with 3 decimal points
 $currency[$from] = sprintf("%.3f",$m[0][0]);
 $currency[$to] = sprintf("%.3f",$m[0][1]);
 
 return $currency;
}


$c = google_currency_converter(2800,"USD");

echo "INR:".$c['INR'];
echo "<br />";
echo "USD:".$c['USD'];



Thursday, September 27, 2012

Website Login with Google Account, Yahoo Account


Make your registration process easily with Google Account OAuth integration along with yahoo.
Website registration and Login forms have important aspect of our development process. Currently visitors were not interested to fill large forms in any website. In this case visitors are not willing to join by signup on our website. In this aspect, technology will a solution. that is open social login from other major services. By this way, we can be use Login from google, yahoo, facebook, twitter.


First, Let us create a open login for our website login or registration form with Google Account and Yahoo Mail. upcoming days we will see other services. Now we can create website Login with OpenID OAuth Login with Google Accounts and Yahoo Accounts.

let us create How to make people login into your website with their Google account and Yahoo
Google and Yahoo provides Federated Login for Account Users with OAuth.

UPDATE:
YAHOO OpenID Identify URL has been changed:
http://open.login.yahooapis.com/openid20/www.yahoo.com/xrds


Step: 1
Download LightOpenID Class from
https://nodeload.github.com/brice/LightOpenId/zipball/master


Step: 2: Write a Following Code and design a Form to Handle Login

<?php session_start();
# Logging in with Google accounts requires setting special identity, so this example shows how to do it.
require 'require/openid.php';

try {
    # Change 'localhost' to your domain name.
    $openid = new LightOpenID('demos.w3lessons.com');
 
  $openid->required = array(
  'namePerson',
  'namePerson/first',
  'namePerson/last',
  'contact/email',
  );

    if(!$openid->mode) {
  
 if(@$_GET['auth']=="google")
    {
  $_SESSION['auth']="Google";
        $openid->identity = 'https://www.google.com/accounts/o8/id';
        header('Location: ' . $openid->authUrl());
 }elseif(@$_GET['auth']=="yahoo")
 {
  $_SESSION['auth']="Yahoo";
  $openid->identity ='http://open.login.yahooapis.com/openid20/www.yahoo.com/xrds';
  header("Location:".$openid->authUrl());
 }

    } elseif($openid->mode == 'cancel') {
        echo 'User has canceled authentication!';
    } else {
   $external_login=$openid->getAttributes();
   $_SESSION['name']=$external_login['namePerson/first']." ".$external_login['namePerson/last'];
   $_SESSION['email']=$external_login['contact/email'];
   header("Location:account-home.php");
   exit();
   
    }
} catch(ErrorException $e) {
    echo $e->getMessage();
}
?>


Download This Script    Live Demo    Download Script



Get MIME type


If you looking for a solution to find the File Content-Type or MIME Type.
Detecting MIME Type of each file extension is necessary to build dynamic file processing in PHP

Example:

// In the following code image/png is MIME type which is assigned dynamically
header("Content-Type:image/png"); 


We can get MIME Type using the following simple php code


Here is the best solution to find the Exact MIME Type of the file using the following simple upload form.

<?php
session_start();

if(isset($_POST['upload']))
{
 $mime_type =  $_FILES['upload_file']['type'];
 $_SESSION['mime_type'][] = $mime_type;
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload and Resize Image</title>
<style type="text/css">
body,td,th {
 font-size: 14px;
 font-family: Verdana, Geneva, sans-serif;
}
body {
 margin-left: 10px;
 margin-right: 10px;
}
</style>
</head>
<body>

<form action="" method="post" enctype="multipart/form-data">
    <fieldset>
    <legend>Upload File in PHP</legend>
    
        <input name="upload_file" type="file" id="upload_file" />
        
        <input name="upload" type="submit" id="upload" value="Upload" />
        
    </fieldset>
</form>

<div style="padding:10px;">
Uploaded File MIME Type is : <br />
<pre>
<?php 
if(is_array(@$_SESSION['mime_type']))
foreach($_SESSION['mime_type'] as $type)
echo @$type."\n"; ?>
</pre>
</div>

</body>
</html>


Download This Script     Live Demo  

Resize Image when upload PHP


Upload and Resize Image dynamically. when upload a image file in PHP is very use full to manage images on web development.
here is my solution how to upload image after resize  uploaded image in PHP


Upload Rezied Image on Server

Upload and Resize Image PHP

Upload-Resize.php (full Source)

<?php

if(isset($_POST['upload_image']))
{
 
 // Check Valid Image 
 if(preg_match("/(jpg)|(png)|(gif)/i",$_FILES['image_file']['name']))
 {
   
 // Load uploaded image from $_FILES
 // encode type in form need to set | encode="multipart/form-data" |
 $filename = $_FILES['image_file']['tmp_name'];
 
 // Prepare target image name with path on server appending with timestamp
 $target_file_name = "Image".time();
 $target_file_name = "images/$target_file_name";  
 
 $image_info = getimagesize($filename);
 $image_type = $image_info[2];


  
  if( $image_type == IMAGETYPE_JPEG ) {
   $image = imagecreatefromjpeg($filename);
   $target_file_name.=".jpg"; // append file extention based on image type;
  } elseif( $image_type == IMAGETYPE_GIF ) {
   $image = imagecreatefromgif($filename);
   $target_file_name.=".gif";  
  } elseif( $image_type == IMAGETYPE_PNG ) {
   $target_file_name.=".png";  
   $image = imagecreatefrompng($filename);
  }
  
  // get width height of upload image file
  $height = imagesy($image);
  $width = imagesx($image);
 
  // SET THE SIZE OF TARGET IMAGE i use 250 x 250
  $target_width = 250;
  $target_height = 250;
  // Create a Empty Image Canvas
  $new_image = imagecreatetruecolor($target_width,$target_height);
  imagealphablending($new_image, true);
  imagesavealpha($new_image, true);
  
  // Set Canvas Background Color / Transparent as per your requirement
  // I prefer to go with Transparent
  
  // Make canvas Filled Background Color
  $white = imagecolorallocate($new_image, 255, 255, 255);
  $grey = imagecolorallocate($new_image, 128, 128, 128);
  $black = imagecolorallocate($new_image, 0, 0, 0);
  imagefilledrectangle($new_image, 0, 0, $target_width,$target_height, $grey); 
  
  // Make Canvas Transparent
  $trans_colour = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
  imagefill($new_image, 0, 0, $trans_colour);
 
  // Copy Source Image to Canvas
  imagecopyresampled($new_image, $image, 0, 0, 0, 0, $target_width,$target_height,$width, $height);
  $image = $new_image;
  

  
  // Save image based on file type;
  if( $image_type == IMAGETYPE_JPEG ) {
   imagejpeg($image,$filename,100);
  } elseif( $image_type == IMAGETYPE_GIF ) {
   imagegif($image,$target_file_name);         
  } elseif( $image_type == IMAGETYPE_PNG ) {
   imagepng($image,$target_file_name);
  }   
   chmod($target_file_name,777);
  
  $response = '<span style="color:#060">Image Successfully Uploaded!</span>';
 }else
 {
  $response = '<span style="color:#FF0000;">Select a Valid (JPG,GIF,PNG) Images</span>';
 }
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload and Resize Image</title>
<style type="text/css">
body,td,th {
 font-size: 14px;
 font-family: Verdana, Geneva, sans-serif;
}
body {
 margin-left: 10px;
 margin-right: 10px;
}
</style>
</head>
<body>

<div style="padding:10px;">
<?php echo @$response; ?>
</div>
<form action="" method="post" enctype="multipart/form-data">
    <fieldset>
    <legend>Upload Image</legend>
    
        <input name="image_file" type="file" id="image_file" />
        
        <input name="upload_image" type="submit" id="upload_image" value="Upload" />
        
    </fieldset>
</form>
</body>
</html>



Tuesday, September 25, 2012

Get PHP script execution time


Get PHP Script executation time with following simple php script

PHP Script Execution Time



<?php
function page_loading_time()
{
    list ($msec, $sec) = explode(' ', microtime());
    $microtime = (float)$msec + (float)$sec;
    return $microtime;
}

// Capture current time at the Begining of the file
$start=page_loading_time();

usleep(100000);  // Delaying page output 0.1 second for testing purpose.
// Your Content Goes here


echo "<br />At the End of the File
";
$end = page_loading_time();
// Print results.
echo 'Page Loading Time: <b>' . round($end - $start, 2) . '</b> seconds';   
?>

Add Image watermark Over another Image PHP


Adding watermark is very help full. Add Image Watermark with original image is also help to protect our images here is my solution to Add Water Mark in PHP

Use the following Images

original_image.jpg




watermark_image.png

water mark image

Prepare an transparent image with exact same size of the original image. Transparent PNG with Text by overlap original image to create a final watermark added image.

<?php
// Original Image Path
$image= "images/original_image.jpg";  

header("Content-type: image/jpeg");
header("Content-Disposition: inline; filename=$image");

switch (TRUE) {
case stristr($image,'jpg') :
$photoImage = ImageCreateFromJPEG("$image");
break;
case stristr($image,'gif') :
$photoImage = ImageCreateFromGIF("$image");
break;
case stristr($image,'png') :
$photoImage = ImageCreateFromPNG("$image");
break;
}

ImageAlphaBlending($photoImage, true); 

// Same Size PNG Watermark Image with Transparency
$logoImage = ImageCreateFromPNG("watermark_image.png"); 
$logoW = ImageSX($logoImage); 
$logoH = ImageSY($logoImage); 

// were you see the two 1's this is the offset from the top-left hand corner!
ImageCopy($photoImage, $logoImage, 1, 1, 0, 0, $logoW, $logoH); 

imagejpeg($photoImage);
// if you want to save add the following line
imagejpeg($photoImage,"images/final.jpg");

ImageDestroy($photoImage); 
ImageDestroy($logoImage); 

?>



Login with Yahoo Account


Website login with Yahoo account been posted at :
Website Login with Yahoo Account in my previous post, yahoo openid identify url been changed.

please use the following new OpenID URL for yahoo in order to work.


NEW Yahoo OpenID URL:

http://open.login.yahooapis.com/openid20/www.yahoo.com/xrds
<?php session_start();
# Logging in with Google accounts requires setting special identity, so this example shows how to do it.
require 'require/openid.php';

try {
    # Change 'localhost' to your domain name.
    $openid = new LightOpenID('demos.w3lessons.com');
 
  $openid->required = array(
  'namePerson',
  'namePerson/first',
  'namePerson/last',
  'contact/email',
  );

    if(!$openid->mode) {
  
 if(@$_GET['auth']=="google")
    {
  $_SESSION['auth']="Google";
        $openid->identity = 'https://www.google.com/accounts/o8/id';
        header('Location: ' . $openid->authUrl());
 }elseif(@$_GET['auth']=="yahoo")
 {
  $_SESSION['auth']="Yahoo";
$openid->identity ='http://open.login.yahooapis.com/openid20/www.yahoo.com/xrds';
  header("Location:".$openid->authUrl());
 }

    } elseif($openid->mode == 'cancel') {
        echo 'User has canceled authentication!';
    } else {
   $external_login=$openid->getAttributes();
   $_SESSION['name']=$external_login['namePerson/first']." ".$external_login['namePerson/last'];
   $_SESSION['email']=$external_login['contact/email'];
   header("Location:account-home.php");
   exit();
   
    }
} catch(ErrorException $e) {
    echo $e->getMessage();
}
?>



View the Updated New Demo & Download

Download This Script     Live Demo     Download Script

Saturday, September 22, 2012

Water mark in PHP


Processing with image in PHP, Adding watermark is very help full. Add Image Watermark with original image is also help to protect our images here is my solution to Add Water Mark in PHP


Prepare an transparent image with exact same size of the original image. Transparent PNG with Text by overlap original image to create a final watermark added image.

<?php
// Original Image Path
$image= "images/original_image.jpg";  

header("Content-type: image/jpeg");
header("Content-Disposition: inline; filename=$image");

switch (TRUE) {
case stristr($image,'jpg') :
$photoImage = ImageCreateFromJPEG("$image");
break;
case stristr($image,'gif') :
$photoImage = ImageCreateFromGIF("$image");
break;
case stristr($image,'png') :
$photoImage = ImageCreateFromPNG("$image");
break;
}

ImageAlphaBlending($photoImage, true); 

// Same Size PNG Watermark Image with Transparency
$logoImage = ImageCreateFromPNG("watermark_image.png"); 
$logoW = ImageSX($logoImage); 
$logoH = ImageSY($logoImage); 

// were you see the two 1's this is the offset from the top-left hand corner!
ImageCopy($photoImage, $logoImage, 1, 1, 0, 0, $logoW, $logoH); 

imagejpeg($photoImage);
// if you want to save add the following line
imagejpeg($photoImage,"images/final.jpg");

ImageDestroy($photoImage); 
ImageDestroy($logoImage); 

?>




Friday, September 21, 2012

Convert Text Area to Array PHP



Processing multiple records through Text Area, We may need to convert that text area values into array from every line of text in that TextArea. here is my solution to "Convert TextArea to Array"



<!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Text Area to Array</title>
</head>
<body>

<?php
// Check Form Submission
if(isset($_POST['submit']))
{
 // Capture cities text into variable
 $text = ucwords($_POST['cities']);
 // Replace entry new line with Comma(,)
 $cities = preg_replace("~\s*[\r\n]+~", ', ', $text);
 // Explode by Comma(,) and trim if any white spaces with array_map
 $cities = array_map('trim',explode(",",$cities));
 // final output as array
 echo "<pre>";
 print_r($cities);
 echo "</pre>";
}


?>

<form action="" method="post">
  <h2>Convert Text Area to Array</h2>
  <p>Enter each city every line<br />
    <textarea name="cities" cols="50" rows="10" id="keywords"></textarea>
    <br />
    <br />
    
    <input name="submit" type="submit" value="Submit Cities" id="submit" />
  </p>
</form>
</body>
</html>



Download This Script     Live Demo