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/

 
include('EmailAddressValidator.php');
 
$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
		$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;
}
 

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;
$xsl->load('something.xsl');
 
// import the XSL styelsheet into the XSLT process
$xp->importStylesheet($xsl);
 
// create a DOM document and load the XML datat
$xml_doc = new DomDocument;
$xml_doc->load('something.xml');
 
// 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));
   }
   xslt_free($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
readfile('myImage.jpg');
 

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/

 
include('Reform.php');
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/

 
include("class.phpmailer.php");
$mail = new PHPMailer();
$mail->From = 'noreply@htmlblog.net';
$mail->FromName = 'HTML Blog';
$mail->Host = 'smtp.site.com';
$mail->Mailer = 'smtp';
$mail->Subject = 'My Subject';
$mail->IsHTML(true);
$body = 'Hello<br/>How are you ?';
$textBody = 'Hello, how are you ?';
$mail->Body = $body;
$mail->AltBody = $textBody;
$mail->AddAddress('asvin [@] gmail.com');
if(!$mail->Send())
	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";
}
else{
    echo 'There has been a mail error !';
}
 
//It's polite to do this when you're finished
$swift->disconnect();
 

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) {
	$uploadedImage->Process('myuploads');
	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
    closedir($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
include('MDB2.php');
 
// connection info
$db =& MDB2::factory('mysql://username:password@host/database');
// set fetch mode
$db->setFetchMode(MDB2_FETCHMODE_ASSOC);
 
// 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
$statement->execute($sqlData);
$statement->free();
 
// disconnect from db
$db->disconnect();
 
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • StumbleUpon
  • Mixx
  • Ma.gnolia
  • Technorati
  • Netvouz
  • Reddit
  • Propeller
  • Slashdot
  • DZone

72 Comments to “10 code snippets for PHP developers”

  1. Human Bagel 4 November 2008 at 12:16 am #

    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. kevin 4 November 2008 at 5:18 am #

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

  3. Ronald 4 November 2008 at 8:13 am #

    Thanks for pointing the way to Swift. Good list.

  4. jesse 4 November 2008 at 8:26 am #

    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. [...] The html blog | 10 code snippets for PHP developers (tags: php) [...]

  6. asvin 4 November 2008 at 9:04 am #

    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.

  7. Askold 4 November 2008 at 2:21 pm #

    nice ideas

  8. Felix 4 November 2008 at 5:09 pm #

    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.

  9. asvin 4 November 2008 at 5:33 pm #

    Thnx Felix, already updated the code ;-)

  10. Cts 4 November 2008 at 5:34 pm #

    Thanks for the nice list.

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

    Witi

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

  11. Raul 4 November 2008 at 6:41 pm #

    nice

  12. Joe McCann 4 November 2008 at 8:16 pm #

    Awesome list…will use for sure.

  13. [...] 10 code snippets for PHP developers [...]

  14. [...]  10 code snippets for PHP developers () [...]

  15. [...] Developers, don’t feel left out this roundup. The HTML Blog provides 10 code snippets for PHP developers. [...]

  16. [...] The html blog | 10 code snippets for PHP developers (tags: webdevelopment webdev webdesign web-design web validation tutorials tutorial tricks) [...]

  17. [...] Ways to Hack Your Brain For A Better Life JD-GUI | Java Decompiler The html blog | 10 code snippets for PHP developers Student emails MIT’s Comp. Sci. mailing list with an OS question. Here is Richard Stallman’s reply. [...]

  18. [...] The html blog | 10 code snippets for PHP developers (tags: php webdesign tutorial blog) [...]

  19. Mandragora 5 November 2008 at 12:20 pm #

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

  20. asvin 5 November 2008 at 12:44 pm #

    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.

  21. doosch 5 November 2008 at 4:14 pm #

    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

  22. [...] The html blog | 10 code snippets for PHP developers More Snippets of greatness for us PHP Developers (tags: web Tutorials webdevelopment validation web-design reference webdesign development howto programming tips tools tricks dev snippets php html webdev blog Resources list bit200f08 shortcuts snippet good programmers code) [...]

  23. [...] The html blog | 10 code snippets for PHP developers http://htmlblog.net/10-code-snippets-for-php-developers/ [...]

  24. [...] buena colección de snippets (trozos de códigos) para programadores php. Entre los que podemos [...]

  25. Konstantin Kovshenin 6 November 2008 at 2:00 pm #

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

  26. madrid web design seo 7 November 2008 at 1:07 pm #

    Good Job! thanks for share!!!

    Greetings

    david

  27. John 9 November 2008 at 6:12 pm #

    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);
    if(!empty($pMatches[2][0]))
    {
    $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 = “”;
    if($userKeyDisp)
    $str .= $k;
    else
    $str .= $val;

    $str .= “”;
    echo $str;
    }
    }

  28. John 9 November 2008 at 6:18 pm #

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

    http://www.abetterframework.com/_include/helpers/file.class.phps

  29. [...] http://htmlblog.net/10-code-snippets-for-php-developers/ [...]

  30. Ivan, Web-Impress 12 November 2008 at 5:20 pm #

    Nice listing, very informative, thanks.

  31. Ivan, Web-Impress 12 November 2008 at 5:22 pm #

    I can’t post my comment!!!

  32. Custom PHP 13 November 2008 at 1:48 am #

    Interesting code samples

  33. Dreams 13 November 2008 at 7:23 am #

    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.

  34. asvin 13 November 2008 at 8:56 am #

    Ivan, the comments are moderated ;-)

  35. Clubit.tv 14 November 2008 at 12:51 pm #

    Great list thanks so much

  36. [...] are 10 bits of code that you can include in your PHP development to do some cool stuff.  Why program it from scratch [...]

  37. Justin 15 November 2008 at 4:40 am #

    scandir does the same thing as dirList function does.

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

  38. Christo 15 November 2008 at 5:29 am #

    Great that solves 2 of my problems instantly!
    Cheers!

  39. Nokia Photos 18 November 2008 at 4:35 am #

    Nice tips, thank you for sharing ;)

  40. Iflexion 25 November 2008 at 1:05 am #

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

  41. [...] código útil en The HTML Blog [Mostrar marcadores] [Cerrar marcadores] [...]

  42. [...] Visit Article [...]

  43. Timothy 5 January 2009 at 10:04 pm #

    Hmmmm. Interesting. Nice list!

  44. [...] Visit Article [...]

  45. [...] Visit Article [...]

  46. jizhiunion 11 January 2009 at 10:55 am #

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

  47. James 26 January 2009 at 12:59 pm #

    damn cool man…

  48. 10 code snippets for PHP developers…

    A compilations of php snippets….

  49. Free book to Success 14 February 2009 at 12:41 pm #

    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?..

  50. free anonymous email send using free smtp 9 March 2009 at 12:06 pm #

    Thanks dude.

    That swift mailer was really good.


Leave a Reply