You are on page 1of 13

PHP Code examples

By
PHP resources

PHP resources

Contents
Contents................................................................................................................ 2
Check for valid email address.............................................................................3
Getting real IP address....................................................................................... 3
Resize Image...................................................................................................... 4
Import CSV File................................................................................................... 5
iPhone & iPod Detection..................................................................................... 5
Display source code of any webpage.................................................................5
Display Facebook fans count..............................................................................5
Download & save a remote image......................................................................6
Send Mail using mail function in PHP..................................................................6
HTTP Redirection................................................................................................ 6
Human Readable Random String .......................................................................6
Parse JSON Data ................................................................................................ 7
Parse XML Data .................................................................................................. 7
Directory Listing in PHP...................................................................................... 8
Unzip a Zip File................................................................................................... 9
Crop Image....................................................................................................... 10
Create Zip Files................................................................................................. 11
Test whether URL exists................................................................................... 12
For more programming information and code..................................................13

PHP resources

Check for valid email address


function is_valid_email($email)
{
if(preg_match("/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/", $email) > 0)
return true;
else
return false;
}

Getting real IP address


function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
//to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}

PHP resources

Resize Image
Creates a thumbnail from an existing image. $filename is the original filename,
while $tmpname is the actual filesystem name (for example, the temporary
filename used in a PHP upload). Returns an image resource which you can then
output to the browser, or save to a file using imagejpg(), imagepng(), etc.

function resize_image($filename, $tmpname, $xmax, $ymax)


{
$ext = explode(".", $filename);
$ext = $ext[count($ext)-1];
if($ext == "jpg" || $ext == "jpeg")
$im = imagecreatefromjpeg($tmpname);
elseif($ext == "png")
$im = imagecreatefrompng($tmpname);
elseif($ext == "gif")
$im = imagecreatefromgif($tmpname);
$x = imagesx($im);
$y = imagesy($im);
if($x <= $xmax && $y <= $ymax)
return $im;
if($x >= $y) {
$newx =
$newy =
}
else {
$newy =
$newx =
}

$xmax;
$newx * $y / $x;
$ymax;
$x / $y * $newy;

$im2 = imagecreatetruecolor($newx, $newy);


imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x,
$y);
return $im2;
}

PHP resources

Import CSV File


$handle = fopen("file.csv", 'r');
while(($data = fgetcsv($handle, 1000, ",")) !== false)
{
list($col1, $col2, ...) = $data;
}
fclose($handle);

iPhone & iPod Detection


if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') ||
strstr($_SERVER['HTTP_USER_AGENT'],'iPod'))
{
header('Location: http://yoursite.com/iphone');
exit();
}

Display source code of any webpage


<?php
$lines = file('http://google.com/');
foreach ($lines as $line_num => $line)
{
// loop thru each line and prepend line numbers
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "\n";
}

Display Facebook fans count


function fb_fan_count($facebook_name)
{
<a
href="https://graph.facebook.com/digimantra">https://graph.facebook.com/digi
mantra</a>
$data = json_decode(file_get_contents("https://graph.facebook.com/".
$facebook_name));
echo $data->likes;
}

PHP resources

Download & save a remote image


$image = file_get_contents('http://www.url.com/image.jpg');
file_put_contents('/images/image.jpg', $image);

Send Mail using mail function in PHP


<?php
$to = "emailaddress@gmail.com";
$subject = "getph[.net";
$body = "Body of your message
$headers = "From: Peter\r\n";
$headers .= "Reply-To: info@programmershelp.net\r\n";
$headers .= "Return-Path: info@ programmershelp.net \r\n";
$headers .= "X-Mailer: PHP5\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to,$subject,$body,$headers);
?>

HTTP Redirection
<?php
header('Location: http://you_stuff/url.php'); // stick your url here
?>

Human Readable Random String


/**************
*@length - length of random string (must be a multiple of 2)
**************/
function readable_random_string($length = 6){
$conso=array("b","c","d","f","g","h","j","k","l",
"m","n","p","r","s","t","v","w","x","y","z");
$vocal=array("a","e","i","o","u");
$password="";
srand ((double)microtime()*1000000);
$max = $length/2;
for($i=1; $i<=$max; $i++)
{
$password.=$conso[rand(0,19)];
$password.=$vocal[rand(0,4)];
}
return $password;
}

PHP resources

Parse JSON Data


$json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":
["wordpress","php"]} '; $obj=json_decode($json_string);
echo $obj->name; //prints foo
echo $obj->interest[1]; //prints php

Parse XML Data


//xml string
$xml_string="<?xml version='1.0'?>
<users>
<user id='398'>
<name>Foo</name>
<email>foo@bar.com</name>
</user>
<user id='867'>
<name>Foobar</name>
<email>foobar@foo.com</name>
</user>
</users>";
//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);
//loop through the each node of user
foreach ($xml->user as $user)
{
//access attribute
echo $user['id'], ' ';
//subnodes are accessed by -> operator
echo $user->name, ' ';
echo $user->email, '<br />';
}

PHP resources

Directory Listing in PHP


<?php
function list_files($dir)
{
if(is_dir($dir))
{
if($handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if($file != "." &amp;&amp; $file != ".." &amp;&amp; $file !=
"Thumbs.db)
{
echo '<a target="_blank" href="'.$dir.$file.'">'.
$file.'</a><br>'."\n";
}
}
closedir($handle);
}
}
}
/*
To use:
<?php
list_files("images/");
?>
*/
?>

PHP resources

Unzip a Zip File


<?php
function unzip($location,$newLocation){
if(exec("unzip $location",$arr)){
mkdir($newLocation);
for($i = 1;$i< count($arr);$i++){
$file = trim(preg_replace("~inflating: ~","",$arr[$i]));
copy($location.'/'.$file,$newLocation.'/'.$file);
unlink($location.'/'.$file);
}
return TRUE;
}else{
return FALSE;
}
}
?>
//Use the code as following:
<?php
include 'functions.php';
if(unzip('zippedfiles/test.zip','unzipped/myNewZip'))
echo 'Success!';
else
echo 'Error';
?>

PHP resources

Crop Image
<?php
$filename= "test.jpg";
list($w, $h, $type, $attr) = getimagesize($filename);
$src_im = imagecreatefromjpeg($filename);
$src_x = '0'; // begin x
$src_y = '0'; // begin y
$src_w = '200'; // width
$src_h = '200'; // height
$dst_x = '0'; // destination x
$dst_y = '0'; // destination y
$dst_im = imagecreatetruecolor($src_w, $src_h);
$white = imagecolorallocate($dst_im, 255, 255, 255);
imagefill($dst_im, 0, 0, $white);
imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
header("Content-type: image/png");
imagepng($dst_im);
imagedestroy($dst_im);
?>

PHP resources

Create Zip Files


function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE :
ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status
of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
/***** Example Usage ***/
$files=array('file1.jpg', 'file2.jpg', 'file3.gif');
create_zip($files, 'myzipfile.zip', true);

PHP resources

Test whether URL exists


function url_exists($url)
{
$hdrs = @get_headers($url);
return is_array($hdrs) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',
$hdrs[0]) : false;
}

PHP resources

For more programming information and code

PHP resources
Programmers help
Programming site

PHP resources

You might also like