Technology and Development
Handy PHP Code Snippets
Send Simple Mail
1 2 3 4 5 6 7 8 9 10 | function send_simple_mail($from,$to,$subject,$body) { $headers = "From: $from\r\n"; $headers .= "Reply-To: $from\r\n"; $headers .= "Return-Path: $from\r\n"; $headers .= "X-Mailer: PHP5\n"; $headers .= 'MIME-Version: 1.0' . "\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n"; @mail($to,$subject,$body,$headers); } |
List a Directory
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Destroy a Directory
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | /***** *@dir - Directory to destroy *@virtual[optional]- whether a virtual directory */ function destroyDir($dir, $virtual = false) { $ds = DIRECTORY_SEPARATOR; $dir = $virtual ? realpath($dir) : $dir; $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir; if (is_dir($dir) && $handle = opendir($dir)) { while ($file = readdir($handle)) { if ($file == '.' || $file == '..') { continue; } elseif (is_dir($dir.$ds.$file)) { destroyDir($dir.$ds.$file); } else { unlink($dir.$ds.$file); } } closedir($handle); rmdir($dir); return true; } else { return false; } } |
Send File via FTP
1 2 3 4 5 6 | $connection = ftp_connect($server); $login = ftp_login($connection, $ftp_user_name, $ftp_user_pass); if (!$connection || !$login) { die('Connection attempt failed!'); } $upload = ftp_put($connection, $dest, $source, $mode); if (!$upload) { echo 'FTP upload failed!'; } ftp_close($connection); |
Zip File
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | /* creates a compressed zip file */ 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); |
UnZip File
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | /********************** *@file - path to zip file *@destination - destination directory for unzipped files */ function unzip_file($file, $destination){ // create object $zip = new ZipArchive() ; // open archive if ($zip->open($file) !== TRUE) { die (’Could not open archive’); } // extract contents to destination directory $zip->extractTo($destination); // close archive $zip->close(); echo 'Archive extracted to directory'; } |
Parse JSON
1 2 3 4 | $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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | //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 />'; } |
Get Client’s real IP address
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Force File Download
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /******************** *@file - path to file */ function force_download($file) { if ((isset($file))&&(file_exists($file))) { header("Content-length: ".filesize($file)); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $file . '"'); readfile("$file"); } else { echo "No file selected"; } } |
Tag Cloud Generation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 ) { $minimumCount = min($data); $maximumCount = max($data); $spread = $maximumCount - $minimumCount; $cloudHTML = ''; $cloudTags = array(); $spread == 0 && $spread = 1; foreach( $data as $tag => $count ) { $size = $minFontSize + ( $count - $minimumCount ) * ( $maxFontSize - $minFontSize ) / $spread; $cloudTags[] = '<a style="font-size: ' . floor( $size ) . 'px' . '" class="tag_cloud" href="#" title="\'' . $tag . '\' returned a count of ' . $count . '">' . htmlspecialchars( stripslashes( $tag ) ) . '</a>'; } return join( "\n", $cloudTags ) . "\n"; } /************************** **** Sample usage ***/ $arr = Array('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43, 'Blur' => 18, 'Canvas' => 33, 'Class' => 15, 'Color Palette' => 11, 'Crop' => 42, 'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode' => 12, 'Encryption' => 30, 'Extract' => 28, 'Filters' => 42); echo getCloud($arr, 12, 36); |
use Gravatars
1 2 3 4 5 6 7 8 9 10 11 12 | /****************** *@email - Email address to show gravatar for *@size - size of gravatar *@default - URL of default gravatar to use *@rating - rating of Gravatar(G, PG, R, X) */ function show_gravatar($email, $size, $default, $rating) { echo '<img src="http://www.gravatar.com/avatar.php?gravatar_id='.md5($email). '&default='.$default.'&size='.$size.'&rating='.$rating.'" width="'.$size.'px" height="'.$size.'px" />'; } |
Resize Image
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | /********************** *@filename - path to the image *@tmpname - temporary path to thumbnail *@xmax - max width *@ymax - max height */ 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; } |
Validate Email Address
1 2 3 4 5 6 7 | function is_valid_email($email) { if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",$email)) return true; else return false; } |
Thanks to jakyra points out that the eregi() function has been deprecated as of php 5.3.0 and completely removed in php 6.0. An alternative would be preg_match_all()
Validate Domain Name
1 2 3 4 5 6 7 | function is_valid_url($url) { if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i', $url)) { echo "Your url is ok."; else echo "Wrong url."; } |
| Print article | This entry was posted by dekarvn on October 14, 2009 at 11:36 am, and is filed under PHP/MySQL. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 10 months ago
Handy!
There is a typo in the first snippet, ‘headers’ is missing its $.
about 10 months ago
Thanks for that, CSky. It’s now fixed. Enjoy XD
about 10 months ago
Your email regex is too restrictive. Pretty much any character can be valid before the @.
After the @, you are restricted to valid domain names.
For example, with gmail, you can use a + in your email address to tag a message sent to your email. Example:
user.host+spam112@gmail.com will be sent to the email account still.
Microsoft allows many other characters too. Right now the best way to validate an email address is to actually send an email and see if it bounces.
about 10 months ago
Validate Email Address uses eregi which is depreciated in 5.3 and removed in 6.0
about 10 months ago
@George: Yes you are absolutely right about the validation progress. The snippet above search for invalid email address while doing form validation. After the from has gone through, it’s (now is a must) to send email with an unique validation link.
@Jakyra: I didn’t know that, I’ll update the post accordingly. Thanks for the tip. I think an alternative would be preg_match()? or preg_match_all() since they’re doing mostly the same thing?
about 10 months ago
I’d suggest using
filter_var($email,FILTER_VALIDATE_EMAIL)
to validate email addresses. It’s built-in PHP5.
http://uk.php.net/manual/en/function.filter-var.php
about 9 months ago
Try this :
http://fr.php.net/manual/fr/class.recursivedirectoryiterator.php
You will be able to list a directory recursively in 2-3 lines…
about 9 months ago
great snippets and very useful the last comment
about 4 months ago
Do you have copy writer for so good articles? If so please give me contacts, because this really rocks!
about 4 months ago
This is such a great resource that you are providing and you give it away for free. I enjoy seeing websites that understand the value of providing a prime resource for free. I truly loved reading your post. Thanks!