Wednesday, July 24, 2019

Dynamic Image Dimension based on Font size in PHP


Working with images and text, we need to set image size based on font size is very useful for dynamic image processing. like CAPTCHA and text images. if you looking for PHP script to set image size based on font size here is the solution for you.

<?php


if($_GET['fontsize']!="" and is_numeric($_GET['fontsize']))
$size=$_GET['fontsize'];
else
$size=20;


define("F_SIZE", $size);
define("F_ANGLE", 0);
define("F_FONT", "verdana.ttf");


$text = "W3 Lessons";

$Leading=0;
$W=0;
$H=0;
$X=0;
$Y=0;

$_bx = imagettfbbox(F_SIZE, F_ANGLE, F_FONT, $text);
$s = preg_split("/\n]+/", $text);  // Array of lines
$nL = count($s);  // Number of lines

$W = ($W==0)?abs($_bx[2]-$_bx[0]):$W;
$H = ($H==0)?abs($_bx[5]-$_bx[3])+2+($nL>1?($nL*$Leading):0):$H;

$W*=1.05;
$H*=1.5;

$img = @imagecreate($W+8, $H) or die("Cannot Initialize new GD image stream");

$white = imagecolorallocate($img, 255,255,255);
$txtColor = imagecolorallocate($img, 29,56,131);

// Adjust padding right:
$W+=8;
$bgwhite = imagecolorallocatealpha($img,238,238,238,0);
imagefilledrectangle($img, 0, 0,$W,$H, $bgwhite);

$alpha = "".range("a", "z");
$alpha = $alpha.strtoupper($alpha).range(0, 9);

// Use the string to determine the height of a line
$_b = imageTTFBbox(F_SIZE, F_ANGLE, F_FONT, $alpha);
$_H = abs($_b[5]-$_b[3]);
$__H = 0;

// Use the string to determine the width of a line
$_b = imagettfbbox(F_SIZE, F_ANGLE, F_FONT, $text);
$_W = abs($_b[2]-$_b[0]);

// Final width and height
$_X = abs($W/2)-abs($_W/2);
$__H += $_H;

imagettftext($img, F_SIZE, F_ANGLE, $_X, $__H, $txtColor, F_FONT, $text);

header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
// END EMAIL IMAGE  
exit();
?>

Full Screen iframe, frameset URL Masking


URL Masking technique with frameset, widely used method and support all modern and old browsers.

<html><head><meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<frameset border="0" rows="100%,*" cols="100%" frameborder="no">
 <frame name="TopFrame" scrolling="yes" noresize src="http://www.w3lessons.com">
 <frame name="BottomFrame" scrolling="no" noresize>

 <noframes></noframes>
</frameset>
</html>

Wednesday, January 24, 2018

PHP Image class with data_uri, resize, crop, watermark, scale, fitTosize



PHP Image manipulation class almost every options in this class.

Following features are included in this PHP class. 

  • data_uri
  • getWidth
  • getHeight
  • resizeToHeight
  • resizeToWidth
  • scale
  • crop
  • resize
  • addWatermark
  • fitToSize



<?php


/*
Written by: Jailani M, http://www.W3Lessons.com
w3_image Image Manipulation Class 
*/
class w3_image {

   var $image;
   var $image_type;

   function load($filename) {
      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if( $this->image_type == IMAGETYPE_JPEG ) {
         $this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {
         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {
         $this->image = imagecreatefrompng($filename);
      }

   }
   
   
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=100, $permissions=null) {
    

imagecolortransparent($this->image, imagecolorallocatealpha($this->image, 0, 0, 0, 127));
imagealphablending($this->image, false);
imagesavealpha($this->image, true);

    
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {
         imagegif($this->image,$filename);         
      } elseif( $image_type == IMAGETYPE_PNG ) {
         imagepng($this->image,$filename);
      }   
      if( $permissions != null) {
         chmod($filename,$permissions);
      }
   }
   
   
 function output($image_type=IMAGETYPE_JPEG) {
  
  imagecolortransparent($this->image, imagecolorallocatealpha($this->image, 0, 0, 0, 127));
  imagealphablending($this->image, false);
  imagesavealpha($this->image, true);  
    
  if( $image_type == IMAGETYPE_JPEG ) {
  imagejpeg($this->image);
  } elseif( $image_type == IMAGETYPE_GIF ) {
  imagegif($this->image);         
  } elseif( $image_type == IMAGETYPE_PNG ) {
  imagepng($this->image);
  }   
 }
 
 function data_uri($image_type=IMAGETYPE_JPEG) {
  
  imagecolortransparent($this->image, imagecolorallocatealpha($this->image, 0, 0, 0, 127));
  imagealphablending($this->image, false);
  imagesavealpha($this->image, true);  
   ob_start();
  if( $image_type == IMAGETYPE_JPEG ) {
  $mime="image/jpeg";
  imagejpeg($this->image);
  } elseif( $image_type == IMAGETYPE_GIF ) {
  $mime="image/gif";   
  imagegif($this->image);         
  } elseif( $image_type == IMAGETYPE_PNG ) {
  $mime="image/png";   
  imagepng($this->image);
  }
  $image_data= ob_get_clean();
  $base64=base64_encode($image_data);
  return "data:$mime;base64,$base64";
 } 
   
   
   function getWidth() {
      return imagesx($this->image);
   }
   function getHeight() {
      return imagesy($this->image);
   }
   function resizeToHeight($height) {
      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }
   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }
   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100; 
      $this->resize($width,$height);
   }
   function resize($width,$height) {
  $new_image = imagecreatetruecolor($width, $height);
  imagealphablending($new_image, false);
  imagesavealpha($new_image, true);   
     imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
     $this->image = $new_image;   
   }  
   
   function crop($left,$top,$width,$height)
   {
 // create a blank image having the same width and height as the crop area
    // this will be our cropped image
    $cropped_image = imagecreatetruecolor($width, $height);
 $bgwhite = imagecolorallocatealpha($cropped_image,255,255,255,0);
 imagefilledrectangle($cropped_image, 0, 0,$width,$height, $bgwhite);
    // copy the crop area from the source image to the blank image created above
    imagecopy($cropped_image, $this->image, 0, 0, $left, $top,$width, $height);
  $this->image = $cropped_image;
   }
   
   function addWatermark($watermark_image,$position="B_RIGHT")
   {
    // T_LEFT, T_RIGHT, B_LEFT, B_RIGHT
    
  ImageAlphaBlending($this->image, true); 
  
  // Same Size PNG Watermark Image with Transparency
  $logoImage = ImageCreateFromPNG($watermark_image); 
  $logoW = ImageSX($logoImage); 
  $logoH = ImageSY($logoImage); 
  
  if($position == "T_LEFT")
  {
  $dst_x = 0;
  $dst_y = 0;
  }elseif($position == "T_RIGHT")
  {
  $dst_x = $this->getWidth()-$logoW;
  $dst_y = 0;
  }elseif($position == "B_LEFT")
  {
  $dst_x = 0;
  $dst_y = $this->getHeight()-$logoH;   
  }elseif($position == "B_RIGHT")
  {
  $dst_x = $this->getWidth()-$logoW;
  $dst_y = $this->getHeight()-$logoH;
  }
  
  
  // were you see the two 1's this is the offset from the top-left hand corner!
  ImageCopy($this->image, $logoImage, $dst_x, $dst_y, 0, 0, $logoW, $logoH);  
   }
   
   function fitToSize($width,$height)
   {
 // create a blank image having the same width and height fitToSize
    // this will be our final image
    $fitToImage = imagecreatetruecolor($width, $height);
 $bgwhite = imagecolorallocatealpha($fitToImage,255,255,255,0);
 imagefilledrectangle($fitToImage, 0, 0,$width,$height, $bgwhite);
    // resize image based on fit to size in both height and width
 $this->resizeToWidth($width);
 
 if($this->getHeight() > $height)
 $this->resizeToHeight($height); 
 
 $_x = ($width - $this->getWidth())/2;
 $_w = $this->getWidth();
 
 $_y = ($height - $this->getHeight()) / 2; 
 $_h = $this->getHeight();
 
 imagecopy($fitToImage,$this->image,$_x,$_y,0,0,$_w,$_h);
  $this->image = $fitToImage;
   }
}



Tuesday, January 23, 2018

Simple Two way Encryption and Decryption Function PHP



Hello guys, after a long time, I came back to my blog with new flavor of articles, and I am plan to concentrate my blog half my working day here after. So my followers can expect valuable development ideas from me through comment and feed.

Here we go our come back article, Here now I teach you the Two way encryption and decryption method with full explanation.

Objective Build a function for Two Way Encryption and Decryption:

            Encrypt as well as Decrypt our given string with our own Encrypt Decrypt Key and Initiative Vector (IV) (?), with Advanced Encryption Standard (AES) (?) this method is highly secure method all time ever with few PHP functions to build Two way Encryption and Decryption.

Functions Involved in Two Day Encryption and Decryption.

hash - Generate a hash value (message digest)
string hash ( string $algo , string $data [, bool $raw_output = false ] )

substr - Return part of a string
            string substr ( string $string , int $start [, int $length ] )

base64_encode - Encodes data with MIME base64
string base64_encode ( string $data )

base64_decode - Decodes data encoded with MIME base64
            string base64_decode ( string $data [, bool $strict = false ] )

openssl_encrypt - Encrypts data
string openssl_encrypt ( string $data , string $method , string $key [, int $options = 0 [, string $iv = "" [, string &$tag = NULL [, string $aad = "" [, int $tag_length = 16 ]]]]] )

openssl_decrypt - Decrypts data
            string openssl_decrypt ( string $data , string $method , string $key [, int $options = 0 [, string $iv = "" [, string $tag = "" [, string $aad = "" ]]]] ) 

Two Encryption & Decryption Function

/*
Written by: Jailani M, http://www.W3Lessons.com
Defineds:
ED_KEY - Encryption and Decription key your choice
IV_KEY - INITIATIVE VECTOR your choice
*/
define("ED_KEY","your_key");
define("IV_KEY","your_iv");

function w3_encode( $string) {
    $encrypt_method = "AES-256-CBC";
    $key = hash( 'md5', ED_KEY );
    $iv = substr( hash( 'md5', IV_KEY ), 0, 16 );
    $encoded_string = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
    return $encoded_string;
}

function w3_decode($string)
{
    $encrypt_method = "AES-256-CBC";
    $key = hash( 'md5', ED_KEY );
    $iv = substr( hash( 'md5', IV_KEY ), 0, 16 );
    $decoded_string = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
    return $decoded_string;
}



Download This Script     Live Demo     Download Script

Wednesday, February 18, 2015

Get Google Page through PHP for Multiple URL

Here is the PHP Script for best solution for Finding PR for multiple URLs hope this very useful for your projects.


Google PageRank Script PHP

Thursday, March 7, 2013

Fix External Broken links PHP


Adding External links may not guarantee to available all time, following code will check header response before redirect the user to that particular url using the following Code.


<?php

$url = "http://www.w3lessons.com";

$user_agent = 
'Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0'

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_USERAGENT,$user_agent);
curl_setopt($ch, CURLOPT_REFERER, "");
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response = curl_exec($ch);


// Then, after your curl_exec call:
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
curl_close($ch);


echo "<pre>";
print_r($header);

// Re
HTTP/1.1 200 OK
Server: Apache/2.2.3 (Red Hat)
Last-Modified: Tue, 03 Jul 2012 15:28:22 GMT
ETag: "bc241f05-1aace1-4c3ee90929180"
Accept-Ranges: bytes
Content-Length: 1748193
Content-Type: application/pdf
Date: Thu, 07 Mar 2013 11:36:42 GMT
Connection: keep-alive




?>

Checking corresponding Content-Type before redirecting user help to improve user experience.




Wednesday, January 9, 2013

Facebook login integration with website, Login with Facebook for websites

Facebook provide OAuth support provides web developers are able to create a Login or Sign In option with Existing Facebook Account without spending more time on new registration on your website.
Herewith we saw how to integrate in to your website using  Login with Facebook Button in easy way.

In Order to Create a "Login with Facebook" for your website you need a Facebook account to generate APP_ID and APP_SECRET, Create a Facebook user account and Navigate to the App Developer Page
http://www.facebook.com/developers/

In Top right  press "Create New App" Button you will navigate to the following screen.


In this App Creation Popup, tell your app Display Name on your Facebook Login Popup. and App Namespace is Unique Identifier on Facebook (all lowercase) Check I Agree and Continue. in next screen expand Website Rown from "Select how your app Integrates with facebook" Section.


put your website URL which actually place the "Login with Facebook" Button. eg: http://www.w3lessons.com/ or In case of Local testing you can put http://localhost/facebooklogin/
 press "Save Changes" on Bottom of that screen register your App on Facbook.

Now Your App is Ready and you can create "Login with Facbook" Button for your website.

1. PHP functions for Server Side handling to get Facebook data and store them to our database.
2. Create Login Button Using Facbook JavaScript SDK
3. Create Logout Button Using Facebook SDK

facebook-login.php  (full Source)
<?php
session_start();
define('YOUR_APP_ID', 'YOUR_APP_KEY_HERE');
define('YOUR_APP_SECRET', 'YOUR_SECRET_KEY_HERE');

function get_facebook_cookie($app_id, $app_secret) { 
    $signed_request = parse_signed_request(@$_COOKIE['fbsr_' . $app_id], $app_secret);
    // $signed_request should now have most of the old elements
    $signed_request['uid'] = $signed_request['user_id']; // for compatibility 
    if (!is_null($signed_request)) {
        // the cookie is valid/signed correctly
        // lets change "code" into an "access_token"
  // openssl must enable on your server inorder to access HTTPS
        $access_token_response = file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=$app_id&redirect_uri=&client_secret=$app_secret&code={$signed_request['code']}");
        parse_str($access_token_response);
        $signed_request['access_token'] = $access_token;
        $signed_request['expires'] = time() + $expires;
    }
    return $signed_request;
}

function parse_signed_request($signed_request, $secret) {
  list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

  // decode the data
  $sig = base64_url_decode($encoded_sig);
  $data = json_decode(base64_url_decode($payload), true);

  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
    error_log('Unknown algorithm. Expected HMAC-SHA256');
    return null;
  }

  // check sig
  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  if ($sig !== $expected_sig) {
    error_log('Bad Signed JSON signature!');
    return null;
  }

  return $data;
}

function base64_url_decode($input) {
  return base64_decode(strtr($input, '-_', '+/'));
}

if (isset($_COOKIE['fbsr_' . YOUR_APP_ID]))
{ 
$cookie = get_facebook_cookie(YOUR_APP_ID, YOUR_APP_SECRET);

$user = json_decode(@file_get_contents(
    'https://graph.facebook.com/me?access_token=' .
    $cookie['access_token']));
 
/*
Uncomment this to show all available variables
echo "<pre>";
 - print_r function expose all the values available to get from facebook login connect.
print_r($user);
 1. Save nessary values from $user Object to your Database
 2. Register a Sesion Variable based on your user account code
 3. Redirect to Account Dashboard
echo "</pre>";
*/
 
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Facebook Login Connect for Website Demo</title>
<style type="text/css">
body,td,th {
 font-family: Verdana, Geneva, sans-serif;
 font-size: 14px;
 color: #333;
}
body {
 margin-left: 50px;
 margin-top: 50px;
}
</style>
</head>
<body>
<?php if (@$cookie) { ?>
<h2>Welcome <?= $user->name ?> </h2> <br />
E-mail ID: <?= $user->email ?>
<br />
<a href="javascript://" onclick="FB.logout(function() { window.location='facebook-login.php' }); return false;" >Logout</a>
<?php } else { ?>
<h2>Welcome Guest! </h2>    
<div id="fb-root"></div>
<fb:login-button perms="email" width="width_value" show_faces="true" autologoutlink="true" size="large">Login with Facebook</fb:login-button>
<?php } ?>
<script src="http://connect.facebook.net/en_US/all.js"></script>   
<script>
 // Initiate FB Object
 FB.init({
   appId: '<?= YOUR_APP_ID ?>', 
   status: true,
   cookie: true, 
   xfbml: true
   });
 // Reloading after successfull login
 FB.Event.subscribe('auth.login', function(response) { 
 window.location.reload(); 
 });
</script>
</body>
</html>
If you have any problem feel free to comment


Download This Script     Facebook Connect Live Demo

Thursday, November 22, 2012

Prevent your website opening in Iframe

One of our client, don't want to load their website inside an iframe any other website. In this case PHP provide an excellent header option to prevent or deny iframe opening of your web pages. In case you are in static html we can use JavaScript to redirect a actual page as browser URL on top.


Google is example website for iframe blocking, you did not open Google website in iframe.

PHP code to prevent iframe loading on dynamic php pages.
<?php
// php header to prevent iframe loading of your web page
header("X-FRAME-OPTIONS: DENY");
?>

Example of prevent iframe loading in PHP pages

<?php
header("X-FRAME-OPTIONS: DENY");
?>
<!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>Iframe Blocker</title>
</head>
<body>

<h1>Welcome</h1>

</body>
</html>




JavaScript code to prevent loading iframe on Static HTML pages

<script type="text/javascript">

// Prevent iframe loading of your web page and redirect to iframe target.
if( (self.parent && !(self.parent===self))
    &&(self.parent.frames.length!=0)){
    self.parent.location=document.location
}
</script>
Example of prevent iframe loading in Static HTML pages

<!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>Iframe Blocker</title>

<script type="text/javascript">
if( (self.parent && !(self.parent===self))
    &&(self.parent.frames.length!=0)){
    self.parent.location=document.location
}
</script>

</head>
<body>
<h1>Welcome</h1>

</body>
</html>

Tuesday, October 30, 2012

MySQL select today and last 30 days records


If you need to select records from MySQL table records with date today and last 30 days records.
based on the Server date.

MySQL select today and last 30 days records


SELECT * FROM posts WHERE 
date_of_create BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE();
In case if your field data type were DATETIME format you need to convert your datetime format into date
SELECT DATE_FORMAT(date_of_create, '%m/%d/%Y') FROM posts
WHERE   date_of_create BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()

Wednesday, October 24, 2012

MySQL Date Functions

Working with date in MySQL is very important for date based query processing. today we going to get some important MySQL date functions frequently used in projects.

Here is the date functions with example queries from Article table  have the column date_of_post

CURDATE() - Return the current date

Example:

SELECT * FROM articles WHERE date_of_post = CURDATE()

 

DAY()   - Return day number from the date column

Example:
SELECT * FROM article WHERE DAY(date_of_post) = 1

 

MONTH() - Return Month number from the date column

Example:
SELECT * FROM article WHERE MONTH(date_of_post) = 2

 

YEAR() – Return year number from the date column

Example:
SELECT * FROM article WHERE MONTH(date_of_post) = 2011

 

LAST_DAY() -  Return Last date as number, From the month of the date column

Example:
SELECT * FROM article WHERE DAY(date_of_post) = LAST_DAY(date_of_post)

 

DAYNAME() - Return day name as string from the date column

SELECT DAYNAME (date_of_post) AS `day_of_post` FROM article

 

MONTHNAME() - Return Month name as string from date column

Example:
SELECT MONTHNAME(date_of_post) as `month_of_post` FROM article

 

QUARTER() - Return Quarter Number as 1 to 4 Format as number

Example:
SELECT QUARTER(date_of_post) AS `post_quarter` FROM article

 

WEEK() - Return Week Number Number (0-53)

Example:
SELECT WEEK(date_of_post) AS `week ` FROM article

Saturday, October 20, 2012

Get Yahoo contacts from address book


Mr. Antony request me how to list all email ids from user's yahoo email account. here is the simple solution to get all Emails from user contact list in yahoo address book.

In order to work with Yahoo Address book we need to create oauth Project on yahoo developer network. let us create it first.

Step: 1


Select My Projects on Top Right below the search box. (You are ask to Login with existing yahoo account)

Step: 2

 Click New Project Button

Step 3:


Select Application Type "Standard"

Step 4: ( Fill your Application as per the form below with your own values)

Step 5: (Get your Project Keys)

Application ID: below the Project Name
Consumer Key and Consumer Secret Inside the Box

Step 6: (Verify your Domain)

 

Step: 7 (Download Yahoo PHP SDK -  Included in Demo Download)



index.php ( Show the Button labled "Get Yahoo Contacts")
<p align="center"><br />

<a href="getContact.php" style="background:#939; color:#FFF; 
padding:10px; font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; 
text-decoration:none; font-size:14px; font-style:italic; margin-top:50px; 
text-align:center;">Get Yahoo Contacts</a></p>

getContacts.php

Get List of contacts using YQL after user access
http://developer.yahoo.com/social/rest_api_guide/contacts_table.html


<?php session_start();

error_reporting(0);

// Replace your Own KEYS 

require("lib/Yahoo.inc");
// Your Consumer Key (API Key) goes here.
define('OAUTH_CONSUMER_KEY', "j0yJmk9M1Zzc0F3YURkV3AwJmQ9WVdrOU5tMVRhSFJETjJNbWNHbzlNVEUxTXpRek9UUTJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD0wMg--");
// Your Consumer Secret goes here.
define('OAUTH_CONSUMER_SECRET', "febded04011a8e6e2f1227b9e24688f2252587a");
// Your application ID goes here.
define('OAUTH_APP_ID', "mShtC7c");
// Call back URL
define('CALL_BACK_URL','http://demos.w3lessons.com/yahoo-contact/getContact.php');

/*
    Consumer Key:
    Consumer Secret:
    Application URL:
    App Domain:

   dj0yJmk9M1Zzc0F3YURkV3AwJmQ9WVdrOU5tMVRhSFJETjJNbWNHbzlNVEUxTXpRek9UUTJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD0wMg--
    afebded04011a8e6e2f1227b9e24688f2252587a
    http://demos.w3lessons.com/yahoo-contact/index.php
    demos.w3lessons.com
 
*/ 

$session = YahooSession::requireSession(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_APP_ID);   

$user = $session->getOwner();

$query = sprintf("select * from social.contacts where guid=me;");  
$response = $session->query($query); 



if(isset($response)){

   foreach($response->query->results->contact as $id){

       foreach($id->fields as $subid){

               if( $subid->type == 'email' )
               $emails[] = $subid->value;
       }
   }
}

$session->clearSession();

echo "<pre>";
print_r($emails);
?>
<br />
<br />
<a href="index.php">Back</a>

Download This Script     Live Demo     Download Script

Friday, October 12, 2012

Change of Domain 301 Redirect htaccess



For SEO best practices, when you change domain name of existing website, we need to setup 301 redirect of all existing web pages exactly to a new domain name. This is very important for Search engines detect a new version of URLs

Using the following htaccess code we will redirect all the existing pages of our website to new.


RewriteEngine On
# Redirect all urls with new domain name
RewriteCond %{HTTP_HOST} ^domainone.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.domainone.com$
RewriteRule ^(.*)$ http://www.domaintwo.com/$1 [r=301,nc]

# Redirect with www of new domain.
RewriteCond %{http_host} ^domaintwo.com [nc]
RewriteRule ^(.*)$ http://www.domaintwo.com/$1 [r=301,nc]

about code will redirect all the existing pages of current website to new website with same request URL.

Thursday, October 11, 2012

Protect email address in web content.


While building web content we may need to include email address. In this case spam bots are may access our web page and collect email address inside our web content. based on this email address extracting script.

The only way to protect Email address inside the content is convert all email address into image.

Here is the solution to convert email address into dynamic text images


email-to-image.php

<?php

define("F_SIZE", 10);
define("F_ANGLE", 0);
define("F_FONT", "verdana.ttf");

$text = base64_decode(base64_decode($_GET['id']));

$Leading=0;
$W=0;
$H=0;
$X=0;
$Y=0;
$_bx = imagettfbbox(F_SIZE, F_ANGLE, F_FONT, $text);
$s = preg_split("/\n]+/", $text);  // Array of lines
$nL = count($s);  // Number of lines

$W = ($W==0)?abs($_bx[2]-$_bx[0]):$W;
$H = ($H==0)?abs($_bx[5]-$_bx[3])+2+($nL>1?($nL*$Leading):0):$H;

$img = @imagecreate($W+8, $H) or die("Cannot Initialize new GD image stream");

$white = imagecolorallocate($img, 255,255,255);
$txtColor = imagecolorallocate($img, 255,50,0);

// Adjust padding right:
$W+=8;
$bgwhite = imagecolorallocatealpha($img,238,238,238,0);
imagefilledrectangle($img, 0, 0,$W,$H, $bgwhite);

$alpha = "".range("a", "z");
$alpha = $alpha.strtoupper($alpha).range(0, 9);

// Use the string to determine the height of a line
$_b = imageTTFBbox(F_SIZE, F_ANGLE, F_FONT, $alpha);
$_H = abs($_b[5]-$_b[3]);
$__H = 0;

// Use the string to determine the width of a line
$_b = imagettfbbox(F_SIZE, F_ANGLE, F_FONT, $text);
$_W = abs($_b[2]-$_b[0]);

// Final width and height
$_X = abs($W/2)-abs($_W/2);
$__H += $_H;

imagettftext($img, F_SIZE, F_ANGLE, $_X, $__H, $txtColor, F_FONT, $text);

header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
// END EMAIL IMAGE  
exit();
?>

index.php

<?php
if(isset($_POST['content']))
{
$content=$_POST['content'];
// Keep line breaks inside textarea
$content=preg_replace("/[\n]/", '<br />', $content);
// Find All email ids inside content
preg_match_all('/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/',$content,$emails);

// Replace as image every email address
foreach($emails[0] as $email)
$content=str_replace($email,'<img src="email-to-image.php?id='.base64_encode(base64_encode($email)).'">',$content);
}
?>
<!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body,td,th {
 font-family: Verdana, Geneva, sans-serif;
 font-size: 12px;
 color: #000;
}
body {
 margin-left: 5px;
 margin-top: 5px;
 margin-right: 5px;
 margin-bottom: 5px;
 margin:0 auto;
 width:750px;
}

textarea { width:750px; font-size:15px; font-family:Verdana, Geneva, sans-serif;}

#content
{
 font-size:13px;
 padding:10px;
 background:#EEE;
 border:1px solid #CCC; 
}

#content img
{

 position:relative;
 margin-bottom:-3px;
}

</style>
</head>
<body>

<br>
<br>
<h1>Protect Email Address inside web content</h1>
<form action="" method="post">
<textarea cols="70" rows="10" name="content">
content mixed with any email address. that email address text will be converted into as image. for example we have info@example.com mail in this text area it will be return as image after the compilation. any no of occurrence will automatically replaced as image 

For Example:
Contact
admin@example.com

Technical
tech@example.com
</textarea>
<br /><br />

<input type="submit" value="Compile" name="submit" /><br />
<br />

</form>

<div id="content">
<?php echo @$content; ?>
</div>
</body>
</html>


Download This Script     Live Demo     Download Script

Wednesday, October 10, 2012

Extract Email ID from Content PHP


In many, CMS development, We may often to check whether any email was found inside the content in this case. Here is the best solution to extract email ids from content using the power of regular expression.

Regular Expression to extract Email IDs from Content.

'/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/'

PHP function to extract All Regular Expression Matches

preg_match_all('/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/',$content,$output);

Sample Content.txt with email id mixed html

<p>example for extracting email id <b>example@gmail.com</b> 
from entire content it mean how many <b>email@example.com</b> 
<b>admin.connnect@example.com</b></p
<?php

//Extract Email ID from content.txt

$whois = file_get_contents("content.txt");
preg_match_all('/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/',$whois,$emails);


echo "<pre>";
print_r($emails[0]);

?>

Output

// OUTPUT


Array
(
    [0] => example@gmail.com
    [1] => email@example.com
    [2] => admin.connnect@example.com
)



Tuesday, October 9, 2012

Optimize All MySQL Tables PHP


If you looking for optimizing MySQL database tables from PHP dynamically, here is a solution to optimize entire tables a database.

Optimizing Tables we need to get Entire table list using "SHOW TABLES" query. as this return entire table names as record, after getting executed of this command call OPTIMIZE TABLE and REPAIR TABLE as per the table needs.

Primary Optimization will failed if the table been damage or corrupt. we will apply REPAIR TABLE

<?php

mysql_connect("localhost","root","");
mysql_select_db("your_db_name");


echo "<br /> OPTIMIZING TABLES ";

$alltables = mysql_query("SHOW TABLES");

// Process all tables.
while ($table = mysql_fetch_assoc($alltables))
{
 foreach ($table as $db => $tablename)
 {
 // Optimize them!
 if(mysql_query("OPTIMIZE TABLE ".$tablename))
  echo "<br>OK Optimized : ".$tablename;
 else
 {
  echo "<br>Error Optimizing Applying Reapir... ".$tablename;
  // Apply Reapirt if Optimization Failed;
  if(mysql_query("REPAIR TABLE ".$tablename))
  echo "Repaired !";
  else
  echo "Error Repairing Table!";
 }
 }
}
mysql_close();
?>




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';   
?>