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-validationclass.
Source and docs: http://code.google.com/p/php-email-address-validation/

$validator = new EmailAddressValidator;
if ($validator->check_email_address('[email protected]')) { 
    // 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 = '[email protected]';  
$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", "[email protected]")){
    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:[email protected]/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

Leave a Reply

Your email address will not be published. Required fields are marked *