10 code snippets for PHP developers

I’ve compiled a small list of some useful code snippets which might help you when writing your PHP scripts…

Email address check

Checks for a valid email address using the php-email-address-validation class.
Source and docs: http://code.google.com/p/php-email-address-validation/

$validator = new EmailAddressValidator;
if ($validator->check_email_address('test@example.org')) { 
    // Email address is technically valid 
else {
    // Email not valid

Random password generator

PHP password generator is a complete, working random password generation function for PHP. It allows the developer to customize the password: set its length and strength. Just include this function anywhere in your code and then use it.
Source : http://www.webtoolkit.info/php-random-password-generator.html

function generatePassword($length=9, $strength=0) {
    $vowels = 'aeuy';
    $consonants = 'bdghjmnpqrstvz';
    if ($strength & 1) {
        $consonants .= 'BDGHJLMNPQRSTVWXZ';
    if ($strength & 2) {
        $vowels .= "AEUY";
    if ($strength & 4) {
        $consonants .= '23456789';
    if ($strength & 8) {
        $consonants .= '@#$%';

    $password = '';
    $alt = time() % 2;
    for ($i = 0; $i < $length; $i++) {
        if ($alt == 1) {
            $password .= $consonants[(rand() % strlen($consonants))];
            $alt = 0;
        } else {
            $password .= $vowels[(rand() % strlen($vowels))];
            $alt = 1;
    return $password;

Get IP address

Returns the real IP address of a visitor, even when connecting via a proxy.
Source : http://roshanbh.com.np/2007/12/getting-real-ip-address-in-php.html

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

XSL transformation

PHP5 version
Source : http://www.tonymarston.net/php-mysql/xsl.html

$xp = new XsltProcessor();

// create a DOM document and load the XSL stylesheet
$xsl = new DomDocument;
// import the XSL styelsheet into the XSLT process

// create a DOM document and load the XML datat
$xml_doc = new DomDocument;

// transform the XML into HTML using the XSL file
if ($html = $xp->transformToXML($xml_doc)) {
	echo $html;
else {
	trigger_error('XSL transformation failed.', E_USER_ERROR);
} // if 

PHP4 version

function xml2html($xmldata, $xsl){
   /* $xmldata -> your XML */
   /* $xsl -> XSLT file */

   $arguments = array('/_xml' => $xmldata);
   $xsltproc = xslt_create();
   xslt_set_encoding($xsltproc, 'ISO-8859-1');
   $html = xslt_process($xsltproc, $xmldata, $xsl, NULL, $arguments);

   if (empty($html)) {
       die('XSLT processing error: '. xslt_error($xsltproc));
   return $html;

echo xml2html('myxmml.xml', 'myxsl.xsl');

Force downloading of a file

Forces a user to download a file, for e.g you have an image but you want the user to download it instead of displaying it in his browser.

header("Content-type: application/octet-stream");

// displays progress bar when downloading (credits to Felix ;-))
header("Content-Length: " . filesize('myImage.jpg'));

// file name of download file
header('Content-Disposition: attachment; filename="myImage.jpg"');

// reads the file on the server

String encoding to prevent harmful code

Web applications face any number of threats; one of them is cross-site scripting and related injection attacks. The Reform library attempts to provide a solid set of functions for encoding output for the most common context targets in web applications (e.g. HTML, XML, JavaScript, etc)
Source : http://phed.org/reform-encoding-library/

Reform::HtmlEncode('a potentially harmful string');

Sending mail

Using PHPMailer
PHPMailer a powerful email transport class with a big features and small footprint that is simple to use and integrate into your own software.
Source : http://phpmailer.codeworxtech.com/

$mail = new PHPMailer();  
$mail->From = 'noreply@htmlblog.net';  
$mail->FromName = 'HTML Blog';  
$mail->Host = 'smtp.site.com';  
$mail->Mailer = 'smtp'; 
$mail->Subject = 'My Subject';
$body = 'Hello<br/>How are you ?';
$textBody = 'Hello, how are you ?';
$mail->Body = $body;  
$mail->AltBody = $textBody;  
$mail->AddAddress('asvin [@] gmail.com');
	echo 'There has been a mail error !';

Using Swift Mailer
Swift Mailer is an alternative to PHPMailer and is a fully OOP library for sending e-mails from PHP websites and applications.
Source : http://swiftmailer.org/

// include classes
require_once "lib/Swift.php";
require_once "lib/Swift/Connection/SMTP.php";
$swift =& new Swift(new Swift_Connection_SMTP("smtp.site.com", 25));
$message =& new Swift_Message("My Subject", "Hello<br/>How are you ?", "text/html");
if ($swift->send($message, "asvin [@] gmail.com", "noreply@htmlblog.net")){
    echo "Message sent";
    echo 'There has been a mail error !';
//It's polite to do this when you're finished

Uploading of files

Using class.upload.php from Colin Verot
Source : http://www.verot.net/php_class_upload.htm

$uploadedImage = new Upload($_FILES['uploadImage']);
if ($uploadedImage->uploaded) {
	if ($uploadedImage->processed) {
		echo 'file has been uploaded';

List files in directory

List all files in a directory and return an array.
Source : http://www.laughing-buddha.net/jon/php/dirlist/

function dirList ($directory) {
    // create an array to hold directory list
    $results = array();

    // create a handler for the directory
    $handler = opendir($directory);

    // keep going until all files in directory have been read
    while ($file = readdir($handler)) {

        // if $file isn't this directory or its parent, 
        // add it to the results array
        if ($file != '.' && $file != '..')
            $results[] = $file;

    // tidy up: close the handler

    // done!
    return $results;

Querying RDBMS with MDB2 (for e.g MySQL)

PEAR MDB2 provides a common API for all supported RDBMS.

Source : http://pear.php.net/package/MDB2

// include MDB2 class

// connection info
$db =& MDB2::factory('mysql://username:password@host/database');
// set fetch mode

// querying data
$query = 'SELECT id,label FROM myTable';
$result = $db->queryAll($query);

// inserting data
// prepare statement
$statement = $db->prepare('INSERT INTO mytable(id,label) VALUES(?,?)');
// our data
$sqlData = array($id, $label);
// execute

// disconnect from db
Be Sociable, Share!

Comments (56)

  1. 12:16 am, November 4, 2008Human Bagel  / Reply

    Great list!
    But, for protection against XSS exploits, without blocking harmless HTML/CSS, check out http://humanbagel.com/opencode.php Click the XSS Protect link, it’s peer reviewed open source. good stuff.

    I especially like the upload files one :)

  2. 5:18 am, November 4, 2008kevin  / Reply

    glob() does the same thing as dirList() and it also supports wildcards such as glob(“*.txt”)

  3. 8:13 am, November 4, 2008Ronald  / Reply

    Thanks for pointing the way to Swift. Good list.

  4. 8:26 am, November 4, 2008jesse  / Reply

    Not that these are terrible, but seriously. People who can’t write these themselves, shouldn’t be programming. All of these things could be done by a noobie with some research.

  5. 9:04 am, November 4, 2008asvin  / Reply

    Exactly Jesse you’re right, these are basic things, but this post prevents them from doing the research, having all the useful things under 1 post and discovering some new classes like class.upload.php, EmailAddress validator.

    To Kevin, thx for the glob function, didn’t know about that.

  6. 2:21 pm, November 4, 2008Askold  / Reply

    nice ideas

  7. 5:09 pm, November 4, 2008Felix  / Reply

    You should include a Content-Length header in the file download example. This way the browser will be able to display a proper progress bar.

  8. 5:33 pm, November 4, 2008asvin  / Reply

    Thnx Felix, already updated the code ;-)

  9. 5:34 pm, November 4, 2008Cts  / Reply

    Thanks for the nice list.

    But for listing files in directory I prefer the DirectoryIterator [1] in the SPL.


    [1] http://de.php.net/manual/de/class.directoryiterator.php

  10. 6:41 pm, November 4, 2008Raul  / Reply


  11. 8:16 pm, November 4, 2008Joe McCann  / Reply

    Awesome list…will use for sure.

  12. 12:20 pm, November 5, 2008Mandragora  / Reply

    Why using the php-email-address-validation class ?
    The function filter_var exists with good filters for mail verification.

  13. 12:44 pm, November 5, 2008asvin  / Reply

    filter_var requires PHP 5.2 whereas the php-email-address-validation class can be hacked to work with PHP4 by just removing public/protected from the functions.

  14. 4:14 pm, November 5, 2008doosch  / Reply

    i agree that all of these are functions that one would encounter if you programmed everyday in a commercial and none commercial environment. I think mixing php4 and 5 oop is not such a great idea

  15. 2:00 pm, November 6, 2008Konstantin Kovshenin  / Reply

    Nice snippets. Thanks. Though the mail validator could just use a regex rather than a whole class…

  16. 1:07 pm, November 7, 2008madrid web design seo  / Reply

    Good Job! thanks for share!!!



  17. 6:12 pm, November 9, 2008John  / Reply

    Here’s a few I’ve written:

    Function will parse the content looking for syntax like this:
    {function name=”functionName” value=”passVariableData”}
    and replace this text with the result of the function. Be sure
    that the function called is accessable by the current page.
    public function parseContent($content)
    $pattern = “/\{function name=(['|\"])(.*)(\\1) value=(['|\"])(.*)(\\4)\}/i”;
    $matches = preg_match_all($pattern, $content, $pMatches);
    $result = call_user_func($pMatches[2][0], $pMatches[5][0]);
    $content = str_replace($pMatches[0][0], $result, $content);
    /* Add more filters to content here */

    return $content;

    Function will parse content and replace any URLs with a hyperlink.
    function parseUrls($originalInput, $target = “_blank”)
    $originalInput = str_replace(“\n”, ” \n”, $originalInput);
    $inputTokens = explode(” “, $originalInput);
    $input = “”;
    foreach($inputTokens as $token)
    if(strlen($token) > 5)
    // check for https://, http://
    if((($pos = strpos($token, “http://”)) !== false) ||
    (($pos = strpos($token, “https://”)) !== false)||
    (($pos = strpos($token, “ftp://”)) !== false))

    $pref = substr($token, 0, $pos);
    $link = substr($token, $pos);

    if(strlen($link) > 8) $token = “$pref” . str_replace(array(“\n”, “\r”, ” “), “”, $link) . ““;

    // check for www.
    else if(strpos($token, “www.”) === 0) {
    $token = “$token“;

    $input .= $token.” “;

    return $input;

    function htmlOptions($theArray, $default = ”, $useKeyVal = false, $useKeyDisp = false)
    foreach($theArray as $k => $val)
    $str = “”;
    $str .= $k;
    $str .= $val;

    $str .= “”;
    echo $str;

  18. 6:18 pm, November 9, 2008John  / Reply

    And here’s a file class I wrote. Very simple and no real documentation but someone might find it interesting/useful:


  19. 5:20 pm, November 12, 2008Ivan, Web-Impress  / Reply

    Nice listing, very informative, thanks.

  20. 5:22 pm, November 12, 2008Ivan, Web-Impress  / Reply

    I can’t post my comment!!!

  21. 1:48 am, November 13, 2008Custom PHP  / Reply

    Interesting code samples

  22. 7:23 am, November 13, 2008Dreams  / Reply

    Thanks for such a time saver. Going to bookmark the code snippets. I know I am going to have to refer back to one of these in the future.

  23. 8:56 am, November 13, 2008asvin  / Reply

    Ivan, the comments are moderated ;-)

  24. 12:51 pm, November 14, 2008Clubit.tv  / Reply

    Great list thanks so much

  25. 4:40 am, November 15, 2008Justin  / Reply

    scandir does the same thing as dirList function does.

    php built in functions are faster, too — so use it. :)

  26. 5:29 am, November 15, 2008Christo  / Reply

    Great that solves 2 of my problems instantly!

  27. 4:35 am, November 18, 2008Nokia Photos  / Reply

    Nice tips, thank you for sharing ;)

  28. 1:05 am, November 25, 2008Iflexion  / Reply

    great codes. We used something similar to get IP address in our contact form.

  29. 10:04 pm, January 5, 2009Timothy  / Reply

    Hmmmm. Interesting. Nice list!

  30. 10:55 am, January 11, 2009jizhiunion  / Reply

    Thanks for this excellent resource……very helpful…….
    I share it on my site(http://www.jizhiunion.com)

  31. 12:59 pm, January 26, 2009James  / Reply

    damn cool man…

  32. 12:41 pm, February 14, 2009Free book to Success  / Reply

    I’ve been searching for PHP codes used for uploading files. At last i found the answer, i even found everything that i need for my exercise. just a Question: How many pages should i create prior to this code?..

  33. 12:06 pm, March 9, 2009free anonymous email send using free smtp  / Reply

    Thanks dude.

    That swift mailer was really good.

  34. 10:15 pm, March 10, 2009ndcisiv  / Reply

    Came across this on a stumble, great tips. Keep up the good work.

  35. 8:21 pm, March 26, 2009Healthy Gossip  / Reply

    These snippets are really really useful and save a lot of development time. Great effort.

  36. 1:35 pm, April 7, 2009KZ  / Reply

    For mailer one

    I dont like PHP mailer, since it requires a SMTP server, which doesnt apply the case if I simply wnat to send mail with the mail() function of the server/host.

  37. 10:26 pm, April 16, 2009eXtreme  / Reply

    Good work!

  38. 6:01 pm, April 17, 2009Giovanni  / Reply

    For list files in directory I use glob()

  39. 8:10 pm, May 1, 2009Rafi B.  / Reply

    I liked the real IP function,
    +1 for PHPMailer

    You should add an example of ADOdb here,
    it’s a great abstraction db layer library.

  40. 10:33 am, May 2, 2009MikeyP  / Reply

    Love Stumble Upon. Thanks for the great info!

  41. 8:48 am, June 20, 2009RyanH  / Reply


    You can use PHP’s mail function with PHPMailer. Instead of $mail->IsSMTP() use $mail->IsMail();

  42. 5:40 am, July 2, 2009Ronald H.  / Reply

    So cool. If you come up with any more, please make a post about them. I also thought you’d like to know there is a great domain name at Godaddy.com that you may be interested in. It’s call PHPDEVELOPING.COM and I think its a good fit for you because your a great PHP programmer. You can contact me at my email address and I’ll help you get to it if you want. Again, just thought you’d like to know.

  43. 3:06 pm, July 7, 2009steve  / Reply

    no responds

  44. 2:55 pm, July 11, 2009Mewp  / Reply

    As for random password generation, i use the following code:

    Returns 8 character string composed of mixed case letters, numbers, “+” and “/”. Secure enough for most cases.

    Also, for reading list of files in a directory, glob(‘*’) can be used.
    Overally, this article seem to overcomplicate everything. There are really simpler, and as effective methods.

  45. 5:46 pm, July 23, 2009Emma  / Reply

    Hey, this is great! I found it on Stumble also, good job.

  46. 5:38 pm, August 18, 2009Deacon  / Reply

    I liked these tips.. Keep up the good work!

  47. 1:02 am, August 21, 2009Dave  / Reply

    Like most lists of PHP code snippets, there are problems with all of these.

    The email validator can be replaced with a single regex. There is an official regex in the RFC. While this one is much better than most email validators, it is rather heavy.

    The password generator is not nearly random enough. Even if you give it the greatest strength setting, it is still depressingly predictable without modifications.

    Whether the password starts with a “vowel” or a “consonant” is dependent on the time with a 1 second resolution. I can force that variable *by hand*. I also know that every second letter in the password is drawn from an extremely small pool of only 8 characters. The remainder of the password is drawn from a pool of 43 characters which isn’t much better.

    The complexity of the password will be 8^5 * 43^4 = 112,027,271,168 if the password is generated on an even second and 8^4 * 43^5 = 602,146,582,528 if it is generated on an odd second. While these numbers might look big, in cryptographic terms, they are tiny.

    They are also generated using rand() which is a pseudo random number generator. If the seed of the PRNG is known, the passwords generated are highly predictable.

    The Reform library was moved from the link you provided to OWASP and then to Google code. http://code.google.com/p/reform/source/browse/trunk/src/php/Reform.inc.php When looking at the code, all it does is return the same string with non-alpha-numeric characters replaced with their numeric html entities. The whole class could be replaced with a single call to the PHP built-in function: htmlentities()

    The functional difference is that characters such as : and ( that have a special meaning in a javascript context would not be converted by the PHP built-in. Nonetheless, a filter that stripped these characters out (or rather, allowed the safe ones through) would be a better idea for user data that is going to end up as potentially executable javascript.code.

    Upload is specifically designed for images and includes functions for processing them. You kind of forgot to mention that.

    As Giovanni said, a single PHP built-in does a better job: glob().

  48. 11:58 am, October 6, 2009Pico RG  / Reply

    Really nice functions, thanks for making this

  49. 9:53 am, December 17, 2009Hire php developers  / Reply

    Thanks for the snippiest these are very useful to my software development team and i share it with them.

  50. 2:44 pm, February 28, 2010meloman mp3 free  / Reply

    I liked these tips.. Keep up the good work!

1 2

Leave a Reply

Allowed Tags - You may use these HTML tags and attributes in your comment.

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Pingbacks (24)

  1. 10:09 pm, November 14, 2008Favicon of wacblog.washcoll.edu10 Code Snippits for PHP Developers
  2. 11:03 am, November 27, 2008Favicon of www.rober.ajamusica.comUn poco de código PHP | RoberBlog
  3. 7:15 am, February 8, 2009Favicon of www.faqpal.comYou are now listed on FAQPAL