The document provides code examples for common PHP tasks like validating emails, resizing images, parsing JSON/XML, sending mail, and zipping/unzipping files. It includes functions for checking email addresses, getting the real IP address, importing CSV files, detecting mobile devices, downloading images, and more. Each code snippet is accompanied by a brief description of its use.
2. 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.....................................................................................................5
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
3. 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
4. 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 = $xmax;
$newy = $newx * $y / $x;
}
else {
$newy = $ymax;
$newx = $x / $y * $newy;
}
$im2 = imagecreatetruecolor($newx, $newy);
imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
return $im2;
}
PHP resources
5. 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/digimantra</a>
$data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
echo $data->likes;
}
Download & save a remote image
PHP resources
6. $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: Peterrn";
$headers .= "Reply-To: info@programmershelp.netrn";
$headers .= "Return-Path: info@ programmershelp.net rn";
$headers .= "X-Mailer: PHP5n";
$headers .= 'MIME-Version: 1.0' . "n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
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
7. 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
11. 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
12. Test whether URL exists
function url_exists($url)
{
$hdrs = @get_headers($url);
return is_array($hdrs) ? preg_match('/^HTTP/d+.d+s+2dds+.*$/',$hdrs[0]) : false;
}
PHP resources
13. For more programming information and code
PHP resources
Programmers help
Programming site
PHP resources