Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, August 24, 2011

Function to Convert RSS to Array using PHP from RSS URL

Working with RSS feed is more usefull to promote your website as well as you can get relevant content for your website from another website using RSS Feed, Let us write a code  how to to get RSS feed content from RSS URL.
 

Tuesday, August 23, 2011

Create Pie Chart using PHP

Using PHP GD Library we can create Pie Chart with  imagefilledarc  function, Let us create a Simple Pie Chart with this function and we will look how to work with pie chart in dynamic content. in future.


Create Pie Chart in PHP

<?php
 
// create image with 320x320
  wit$image = imagecreatetruecolor(320, 320);
 
// create Color Schemes for Pie Chart
$black= imagecolorallocate($image, 0,0,0);
imagecolortransparent( $image, $black );

$gray     = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);
$darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90);
$navy     = imagecolorallocate($image, 0x00, 0x00, 0x80);
$darknavy = imagecolorallocate($image, 0x00, 0x00, 0x50);
$red      = imagecolorallocate($image, 0xFF, 0x00, 0x00);
$darkred  = imagecolorallocate($image, 0x90, 0x00, 0x00);
 
// Make look of 3D effect with 10 degree angular
for ($i = 180; $i > 160; $i--) {
   imagefilledarc($image, 160, $i, 300, 160, 0, 135, $darknavy, IMG_ARC_PIE);
   imagefilledarc($image, 160, $i, 300, 160, 135, 225 , $darkgray, IMG_ARC_PIE);
   imagefilledarc($image, 160, $i, 300, 160, 225, 360 , $darkred, IMG_ARC_PIE);
}
 
imagefilledarc($image, 160, 160, 300, 160, 0, 135, $navy, IMG_ARC_PIE);
imagefilledarc($image, 160, 160, 300, 160, 135, 225 , $gray, IMG_ARC_PIE);
imagefilledarc($image, 160, 160, 300, 160, 225, 360 , $red, IMG_ARC_PIE);
 
// output image to browser
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>



Create SEO Friendly Page or Slug URL using PHP

Creating Search Engine Friendly  page URL from your Page Title / heading will very helpful to generate a Highly optimized keyword rich URLs for your Website,  Here is the function to get the Search Engine Friendly SEO Friendly Page URL from given string. while you are generating Dynamic content.


<?php

$PageTitle="<h1>Education 's and Cultural <pre>Programs\" for <br> schools! and colleges!  (2010-11)</h1>";

// @ Desc: Prepare SEO Friendly URL 
// @ Parm: String with Mixed with tags and special characters 
// @ Return: SEO Frinedly URL out by replacing spaces and special characters with Hyphen(-)
function prepare_seo_friendly_url($string)
{
	// Remove HTML Tags if found
	$string=strip_tags($string);
	// Replace special characters with white space
	$string=preg_replace('/[^A-Za-z0-9-]+/', ' ', $string);
	// Trim White Spaces and both sides
	$string=trim($string);
	// Replace whitespaces with Hyphen (-) 
	$string=preg_replace('/[^A-Za-z0-9-]+/','-', $string);	
	// Conver final string to lowercase
	$slug=strtolower($string);
	return $slug;
}

// Example Output:
echo prepare_seo_friendly_url($PageTitle);

// Output:
// education-and-cultural-programs-for-schools-and-colleges-2010-11
?>

Saturday, August 20, 2011

PHP Function to Get Alexa Traffic Rank



To get the Alexa Traffic Rank is very informative to show in your Back office Interface or Admin Panel dashboard to know website traffic details instantly. Most of the clients are request to show Alexa Rank on Admin Panel here is the Script to get Alexa Traffic Rank.

Function to get Alexa Rank.

<?php

function alexaRank($domain){
    $remote_url = 'http://data.alexa.com/data?cli=10&dat=snbamz&url='.trim($domain);
    $search_for = '<POPULARITY URL';
 $part = NULL;
    if ($handle = @fopen($remote_url, "r")) {
        while (!feof($handle)) {
            $part .= fread($handle, 100);
            $pos = strpos($part, $search_for);
            if ($pos === false)
            continue;
            else
            break;
        }
        $part .= fread($handle, 100);
        fclose($handle);
    }
    $str = explode($search_for, $part);
    $str = @array_shift(explode('" SOURCE="panel"/>', $str[1]));
    $str = explode('TEXT="', $str);

    return $str[1];
}


echo alexaRank("google.co.in");

?>


Thursday, August 18, 2011

Create Dynamic Bar Chart in PHP

Using PHP GD Library Functions. we can create Bar chart in php with dynamic data,
here is my SimpleBar Chart class to create a dynamic bar chart for your projects. you can easily add any number of columns and values also you can change your color scheme on base class.

Sample Bar Chart Using SimpleBar.class.php

Wednesday, August 17, 2011

Create Thumbnail on Fly with Data URI in PHP

Thumbnail on fly is very useful trick to reduce page load also gain page loading speed when loading a page from server. But Thumbnail is also stored as a Image file and retrieved from server with http request. If your website getting high volume traffic you need to consider http request by reducing number of Request. Now days the Modern browsers support Image Data URI. data URIs have now been implemented in most browsers.


Here is the Function to Generate Thumbnail on Fly with Data URI

<?php
// Funtion to prepare Data URI:
// @ parm: Image filepath, Image Size
// reutn : data_uri string
function thumbnail_data_uri($filename,$width=0,$height=0) 
{
 
 // Get Image Header Type
      $image_info = getimagesize($filename);
      $image_type = $image_info[2];

 // Check the Size is Specified
 if($width!=0 and $height!=0)
 {
      if( $image_type == IMAGETYPE_JPEG ) {
         $image = imagecreatefromjpeg($filename);
      } elseif( $image_type == IMAGETYPE_GIF ) {
         $image = imagecreatefromgif($filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {
         $image = imagecreatefrompng($filename);
   imagealphablending($image, true);

      } 

 $new_image = imagecreatetruecolor($width, $height);
 imagealphablending($new_image, false);
 imagesavealpha($new_image, true);     
      imagecopyresampled($new_image, $image, 0, 0, 0, 0, $width, $height, imagesx($image),imagesy($image));
      $image = $new_image; 
   
 ob_start();
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($image);
      } elseif( $image_type == IMAGETYPE_GIF ) {
         imagegif($image);         
      } elseif( $image_type == IMAGETYPE_PNG ) {
         imagepng($image);
      } 
 $content=ob_get_clean();   
   
   
 }else
 $content=file_get_contents($filename,true);
 
 
 
 $base64 = base64_encode($content); 
 return "data:$image_type;base64,$base64";
}

?>
<img src="<?php echo thumbnail_data_uri('images/sample.png',200,200);?>" alt="An Earth">
<img src="<?php echo thumbnail_data_uri('images/sample.png',100,100);?>" alt="An Earth">
<img src="<?php echo thumbnail_data_uri('images/sample.png',150,150);?>" alt="An Earth">

<img src="<?php echo thumbnail_data_uri('images/sample.png',100,100);?>" alt="An Earth">
Data URI Advantages

  • HTTP request and header traffic is not required for embedded data, so data URIs consume less bandwidth whenever the overhead of encoding the inline content as a data URI is smaller than the HTTP overhead. For example, the required base64 encoding for an image 600 bytes long would be 800 bytes, so if an HTTP request required more than 200 bytes of overhead, the data URI would be more efficient
  • For transferring many small files (less than a few kilobytes each), this can be faster. TCP transfers tend to start slowly. If each file requires a new TCP connection, the transfer speed is limited by the round-trip time rather than the available bandwidth. Using HTTP keep-alive improves the situation, but may not entirely alleviate the bottleneck.
  •  When browsing a secure HTTPS web site, web browsers commonly require that all elements of a web page be downloaded over secure connections, or the user will be notified of reduced security due to a mixture of secure and insecure elements. On badly configured servers, HTTPS requests have significant overhead over common HTTP requests, so embedding data in data URIs may improve speed in this case.
  • Web browsers are usually configured to make only a certain number (often two) of concurrent HTTP connections to a domain,[6] so inline data frees up a download connection for other content.
  • Environments with limited or restricted access to external resources may embed content when it is disallowed or impractical to reference it externally. For example, an advanced HTML editing field could accept a pasted or inserted image and convert it to a data URI to hide the complexity of external resources from the user. Alternatively, a browser can convert (encode) image based data from the clipboard to a data URI and paste it in a HTML editing field. Mozilla Firefox 4 supports this functionality.
  • It is possible to manage a multimedia page as a single file.
  • Email message templates can contain images (for backgrounds or signatures) without the image appearing to be an "attachment".
  • Data URIs make it more difficult for security software to filter content

Preserve PNG Transparency when resizing image in PHP


For Image manipulation PHP offers variety of functions. When working the Image processing in live projects, thumbnail of fly. Image Resize is often used by us.  Working thumbnails and resize process. The Image Format such JPEG is not a problem but working with PNG, GIF Images with Transparency it creates a block overlay on alpha channel. Here is my solution to resolve this Issue of Alpha fixes.


<?php
header('Content-Type: image/png');
// Set New widht and height of the Image
$newwidth=200;
$newheight=200;

// Create place holder for new size
$new_image = imagecreatetruecolor($newwidth, $newheight);
// Apply aplha bleding and alpha save
imagealphablending($new_image, false);
imagesavealpha($new_image, true);  

// Load Original PNG Image
$source = imagecreatefrompng("sample.png");
// Apply Alpha Blending
imagealphablending($source, true);
// Copy Source image to New Image
imagecopyresampled($new_image, $source, 0, 0, 0, 0, $newwidth, $newheight, imagesx($source), imagesy($source));
// Out put the new resized image with Transparency.
imagepng($new_image);
?>


Tuesday, August 16, 2011

Check Valid Domain Name and Valid TLD in PHP

Check the domain name is valid Domain Name and Domain extension is valid TLD.  When working this task I want to find the solution to check the domain name is valid TLD and the valid domain name. with the power of Regular Expression. Here is the solution to check the given domain name is valid TLD and valid name.

Following function will full fill the following needs:
  • Domain Name Must contain Alpha Numeric 
  • Only special character (-) hyphen. is allowed on domain names.
  • Check the generic domain extension (.com, .edu, .gov, .int, .mil, .net, and .org)
  • All International domain extensions (TLDs) approved by ICANN

valid-domain-name.php
<?php

// @ Desc: Function to check the Given Domain Name is Valid Domain Name and Valid TLD
// @ Parm: domain name : eg: example.com
// @ Return: 0 or 1 (for Valid Domain Name)
function is_valid_domain_extension($domain)
{
	return preg_match('/^([a-z0-9]([-a-z0-9]*[a-z0-9])?\\.)+((a[cdefgilmnoqrstuwxz]|aero|arpa)|(b[abdefghijmnorstvwyz]|biz)|(c[acdfghiklmnorsuvxyz]|cat|com|coop)|d[ejkmoz]|(e[ceghrstu]|edu)|f[ijkmor]|(g[abdefghilmnpqrstuwy]|gov)|h[kmnrtu]|(i[delmnoqrst]|info|int)|(j[emop]|jobs)|k[eghimnprwyz]|l[abcikrstuvy]|(m[acdghklmnopqrstuvwxyz]|mil|mobi|museum)|(n[acefgilopruz]|name|net)|(om|org)|(p[aefghklmnrstwy]|pro)|qa|r[eouw]|s[abcdeghijklmnortvyz]|(t[cdfghjklmnoprtvwz]|travel)|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw])$/i',$domain);
}

// Example example.mz 
// .MZ the domain for Republic of Mozambique
// I aware of the Region when I am working for this function.
echo is_valid_domain_extension("example.mz"); // 

?>

Monday, August 15, 2011

Connect Multiple MySQL Database in PHP

If your website move on to a traffic worthy website. you need to work with multiple database for load balancing and overhead distribution. So we need to work with multiple database on single project. MySQL and PHP provide some efficient logic to handle multiple database on single project. Let us see how to work with Multiple database in efficient way.



Example Project working with Multiple Database.

include/connectdb.php

<?php
// Define Connection Details
define(DB_SERVER,"localhost");
define(DB_USER,"root");
define(DB_PASSWORD,"");

// Define Database Names and Table Names
define(DB_CUSTOMER,"w3lessons_customer_db");
define(DB_SERVICE,"w3lessons_service_db");

// Define Table Name prefix with database name
// For Customer Table
define(TBL_CUSTOMER,DB_CUSTOMER.".tbl_customers");
// For Service Table
define(TBL_SERVICE,DB_SERVICE.".tbl_services");

// Connect MySQL Server
$conn=mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD);
?>

index.php

<?php
include("include/connectdb.php");

if(isset($_POST['customer_id']) and $_POST['customer_id']!="")
{
	$sql="select * from ".TBL_CUSTOMER." where customer_id='{$_POST['customer_id']}'";
	$result=mysql_query($sql);
	$row=mysql_fetch_array($result);

//	$customer_id=$row['customer_id'];
//	$email_id=$row['email_id'];
//	$service_id=$row['service_id'];
// Instead of above three lines we can use	
	extract($row);
}
?>
<!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>Working with Multiple Database :Service Update</title>
<style type="text/css">

<!--
body,td,th {
	font-family: Verdana, Geneva, sans-serif;
	font-size: 11px;
	color: #000;
	font-weight: bold;
}
body {
	margin-left: 10px;
	margin-top: 10px;
}
-->
</style></head>

<body>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post" id="thisForm">

<table border="0" cellspacing="0" cellpadding="7" style="border:1px solid #999;">
  <tr>
    <td colspan="2" bgcolor="#D6D6D6">Customer Service Update Sheet</td>

    </tr>
  <tr>
    <td>Customer Name</td>
    <td><select name="customer_id" id="customer_id" onchange="javascript:document.getElementById('thisForm').submit()">

      <option value="">Select Customer</option>
      <?php
	// Load Service Names from Customer DB
	$sql="select * from ".TBL_CUSTOMER;
	$result=mysql_query($sql);
	while($row=mysql_fetch_array($result))
	{
		if($row['customer_id']==$customer_id)
		echo '<option value="'.$row['customer_id'].'" selected="selected">'.$row['customer_name'].'</option>';
		else		
		echo '<option value="'.$row['customer_id'].'">'.$row['customer_name'].'</option>';
	}							  
	?>

    </select></td>
    </tr>
  <tr>
    <td>Customer Email ID</td>
    <td><input name="email_id" type="text" id="email_id" value="<?=@$email_id?>" /></td>

    </tr>
  <tr>
    <td>Service Requirement</td>
    <td>
      <select name="select" id="select">

        <?php
	// Load Service Names from Service DB
	$sql="select * from ".TBL_SERVICE;
	$result=mysql_query($sql);
	while($row=mysql_fetch_array($result))
	{
		if($row['service_id']==$service_id)
		echo '<option value="'.$row['service_id'].'" selected="selected">'.$row['service_name'].'</option>';
		else
		echo '<option value="'.$row['service_id'].'">'.$row['service_name'].'</option>';
	}							  
	?>

        </select>
    </td>
    </tr>
  </table>
<br />
<br />
<a href="http://www.w3lessons.com/">View Article for Working with Multiple Database</a>

</form>
</body>
</html>

Output:






Download This Script     Download Script

Sunday, August 14, 2011

Function to Calculate PHP Script Execution Time

PHP Script execution time response is important for quick responsive script, we can able to measure our script execution time with the following script. based on this we can optimize our Script Efficiency








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

$start=process_microtime ();

// Your PHP Code Block and Process
sleep(1);

echo "<br/>";
$end = process_microtime();
// Print results.
echo 'Script Execution Time: <b>' . round($end - $start, 3) . '</b> seconds';   

?>

Regular Expressions in PHP for From Validation

As you working in any project regular expressions are very usefull to Form Validation,
here is some of Regular expression which is frequently used for form validation:

  • Email Validation
  • Mobile/Phone Number validation
  • Strong Password validation
  • IP Address Validation
  • Uploaded Image File Validation

<?php

// Valid Email Address Number or Not

	$email="master@example.com";
	if(preg_match('/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/',$email))
	{
		echo "<br>Valid Email Address";
	}else
	{
		echo "<br>Invalid ";
	}
	
// Valid Phone Number or Not

	$phone="434-333-4454";
	if(preg_match('/[(]?\d{3}[)]?\s?-?\s?\d{3}\s?-?\s?\d{4}/',$phone))
	{
		echo "<br>Valid Phone Number";
	}else
	{
		echo "<br>Invalid Phone Number";
	}
	

// Valid Strong Password or Not (Check password with Digits Caps Small Letters symols )

	$password="A4z#s3";
	if(preg_match('/(?!^[0-9]*$)(?!^[a-zA-Z!@#$%^&amp;*()_+=<&gt;?]*$)^([a-zA-Z!@#$%^&amp;*()_+=<&gt;?0-9]{6,15})$/',$password))
	{
		echo "<br>Strong Password";
	}else
	{
		echo "<br>Weak Password";
	}
	

// Valid IPv4 Address or Not 0.0.0.0 to 255.255.255.255

	$ipaddress="128.222.234.182";
	if(preg_match('/\b[12]{1}(?(?<=2)[0-5]|[0-9])?(?(?<=25)[0-5]|[0-9])?\.[12]?(?(?<=2)[0-5]|[0-9])?(?(?<=25)[0-5]|[0-9])?\.[12]?(?(?<=2)[0-5]|[0-9])?(?(?<=25)[0-5]|[0-9])?\.[12]{1}(?(?<=2)[0-5]|[0-9])?(?(?<=25)[0-5]|[0-9])?\b/',$ipaddress))
	{
		echo "<br>Valid IP Address";
	}else
	{
		echo "<br>Invalid IP Address";
	}

// Valid Image or Not (jpg|gif|png)

	$imagefile="mypicture.jpg";
	if(preg_match("/^[a-zA-Z0-9-_\.]+\.(jpg|gif|png)$/",$imagefile))
	{
		echo "<br>Valid Image file";
	}else
	{
		echo "<br>Invalid Image file";
	}
	
?>


Process Two Submit Buttons on single Form for different actions

Working with multiple submit form is very useful idea to perform multiple action in single form. For example we can use this structure for Trial and Full Version download, Save and Save Draft,

<?php
if(isset($_POST['download']))
{
	//Choose a File Based on Submit Button	
	if($_POST['download']=="Download Trail Version")
	$file="TrialVersion.exe";
	elseif($_POST['download']=="Download Full Version")
	$file="FullVersion.exe";

	header('Content-type: application/octet-stream');
	header("Content-length:".filesize($file));
	header('Content-Disposition: filename="'.basename($file).'"');		
	readfile($file,true);
	exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

</head>

<body>
<form id="form1" name="form1" method="post" action="<?=$_SERVER['PHP_SELF']?>">

<input type="submit" name="download" value="Download Trail Version" />
<input type="submit" name="download" value="Download Full Version" />

</form>
</body>
</html>

Saturday, August 13, 2011

Simple Trick to Find File Content Type in PHP

When processing file from server side we need a Exact document Content-Type header define required to process a content type properly.

From the following php header parameter have "Content-Type": audio/mpeg. The String "audio/mpeg" is the content type of the file which we need to process a proper format disposition from server to client.

header('Content-type: audio/mpeg');
Here is the Simple Trick to find the document Content-Type header string
<?php

if(isset($_POST['upload']))
{
	echo "<pre>";
	print_r($_FILES);
	echo "</pre>";
}

?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Simple Trick to Find File Content Type in PHP</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="<?=$_SERVER['PHP_SELF']?>" enctype="multipart/form-data">

<input name="filename" type="file" />
<input type="submit" name="upload" value="Check Content Type" />

</form>
</body>
</html>