Really Useful Tools For PHP Developers

PHP is one of the most widely used language for creating dynamics websites and applications. PHP frameworks like Zend, CakePHP, CodeIgniter, etc and open source PHP classes & libraries have made our lives significantly easy.

Whether you are a PHP novice or an experienced developer; tools that you use have direct impact on your productivity. W3Avenue has compiled a list of really useful extensions & tools for PHP developers that will help you speed up development and significantly improve overall quality of your code.

Free open-source PHP accelerator, optimizer, and dynamic content cache. It increases the performance of PHP scripts by caching them in their compiled state, so that the overhead of compiling is almost completely eliminated. It also optimizes scripts to speed up their execution. eAccelerator typically reduces server load and increases the speed of your PHP code by 1-10 time.

The ionCube PHP Accelerator is an easily installed PHP Zend engine extension that provides a PHP cache, and is capable of delivering a substantial acceleration of PHP scripts without requiring any script changes, loss of dynamic content, or other application compromises.

Build System

A project build system based on Apache Ant. You can do anything with it that you could do with a traditional build system like GNU make, and its use of simple XML build files and extensible PHP “task” classes make it an easy-to-use and highly flexible build framework. Features include running PHPUnit and SimpleTest unit tests, file transformations, file system operations, interactive build support, SQL execution, CVS/SVN operations, tools for creating PEAR packages, and much more.

Code

Beautify PHP is a completely free service that allows visitors to properly format their PHP code according to PEAR standards.

This program reformat and beautify PHP 4 and PHP 5 source code files automatically. The program is Open Source and distributed under the terms of PHP Licence. It is written in PHP 5 and has a command line tool.

an open source PHP code generator which automatically generates clean & tested Object Oriented code for your PHP4/PHP5 application. By generating PHP objects with integrated CRUD methods, POG gives you a head start in any project.

UML2PHP5 is a plugin designed to fit on the Dia diagram application. It automatically generates the PHP code structure following the diagram’s classes.

Instant SQL Formatter is a free online SQL tidy tool. In addition to beautifying SQL code, It can translate SQL code into C#, Java, PHP, DELPHI and other program languages. It also allows you to find out all database objects such as table, column, function in SQL by selecting output format to list database object.

MySQL Table Editor and PHP Code Generator. Important features offered by phpMyEdit are: table manipulation code generation; record addition, change, view, copy and removal; table paging, sorting and filtering; lookups into other tables (1:M bindings); permission configuration; multiple navigation style possibilities; output design control using CSS; logging user actions; Multilanguage support;ability to extend base class.

Encodes and obfuscates PHP code to make the output difficult to reverse engineer. The application requires no pre-modifications to your code and no additional components on your server. This product allows for encoding of functions, variables and the removal of whitespace.

A PHP obfuscator that turns normal, easy to read PHP code into gibberish; with little to no loss of speed and no loss of compatibility.

Database

Enables PHP developers to access data services created using ADO .NET Data Services framework. The goal is to provide the similar functionality as .NET library to access and modify the data and its relationship using URIs which points to pieces of data integrated with the web.

Propel is an Object-Relational Mapping (ORM) framework for PHP5. It allows you to access your database using a set of objects, providing a simple API for storing and retrieving data.

An object oriented library written in PHP that abstracts database operations for portability. It is modeled on Microsoft’s ADO, but has many improvements that make it unique (eg. Pivot Tables, Active Record support, generating HTML for paging recordsets with next and previous links, cached recordsets, HTML menu generation, etc). Supports large number of databases including: MySQL, PostgreSQL, Interbase, Firebird, Informix, Oracle, MS SQL, Foxpro, Access, ADO, Sybase, FrontBase, DB2, SAP DB, SQLite, Netezza, LDAP, and generic ODBC, ODBTP.

Doctrine is an object relational mapper (ORM) for PHP 5.2.3+ that sits on top of a powerful database abstraction layer (DBAL). One of its key features is the option to write database queries in a proprietary object oriented SQL dialect called Doctrine Query Language (DQL), inspired by Hibernates HQL. This provides developers with a powerful alternative to SQL that maintains flexibility without requiring unnecessary code duplication.

Debugging

The Xdebug extension helps you debug your script by providing a lot of valuable information. The debug information that Xdebug can provide includes: stack traces and function traces in error messages, memory allocation and protection for infinite recursions. Xdebug also provides: profiling information for PHP scripts, code coverage analysis, capabilities to debug your scripts interactively with a debug client. You should also check: Webgrind – Xdebug Profiling Web Frontend in PHP, MacGDBp – Mac OS X application that remotely debug their running PHP applications powered by Xdebug.

FirePHP is ideally suited for AJAX development where clean JSON and XML responses are required. FirePHP enables you to log to your Firebug Console using a simple PHP method call. All data is sent via response headers and will not interfere with the content on your page.

DBG is a a full-featured PHP debugger, an interactive tool that helps you debugging php scripts. It works on a production and/or development WEB server and allows you debug your scripts locally or remotely, from an IDE or console.

Provides assistance in debugging PHP code, by program trace, variables display, process time, included files, queries executed, watch variables… This information is gathered through the script execution and therefore are displayed at the end of the script (in a nice floating div or a html table) so that it can be read and used at any moment.
* More: Debuglib, Krumo

Development

PHP CodeSniffer is a PHP5 script that tokenizes and “sniffs” PHP code to detect violations of a defined set of coding standards. It is an essential development tool that ensures that your code remains clean and consistent. It can even help prevent some common semantic errors made by developers.

Similar to Javadoc, and written in php, phpDocumentor can be used from the command line or a web interface to create professional documentation from php source code. phpDocumentor has support for linking between documentation, incorporating user level documents like tutorials and creation of highlighted source code with cross referencing to PHP general documentation.

PHP Depend is software analyzer and metric tool which aims to provide many useful information about a specified PHP project. PHP Depend can generate a large set of software metrics from a given code base, these values can be used to measure the quality of a software project and they help to identify that parts of an application where a refactoring should be applied.

A Firefox add-on that will allow you to easily translate language files and variables in your PHP scripts.

IDE & Editors

Aptana PHP is the robust, free, open source IDE for PHP featuring everything you need to get started fast and get even faster with developing, testing, tuning, and deploying your PHP apps. From pre-installed PHP servers, code assist, code templates, code generation, debugging, refactoring, Smarty editor, database tools and more, Aptana PHP gives you the end-to-end tools you need for PHP plus all the rest that Aptana Studio has to offer.

PHPEclipse runs on all the major OS platforms and has the following features: Syntax Coloring, Brackets Matching, Code folding, Code Completion, PHP Manual integration, Code templates, XDebug support, DBG Support, CVS & SVN++ support.

A professional-grade development environment that includes PHP code editing, debugging, profiling, unit testing, diagnostics and more.

A web based free Integrated Development Environment for the PHP language, in other words it is an application that gives developers all the code editing capabilities they need to develop PHP applications online. It includes a real-time syntax code editor with support for all web formats and a powerful FTP editor.

VS.Php is a PHP integrated development environment based on Visual Studio 2008. With VS.Php you can design, develop, debug and deploy PHP applications within the Visual Studio IDE.
* More: NetBeans, PhpED, PHPEdit, phpDesigner, TextMate, Komodo IDE

Security

A simple to use, well structured, fast and state-of-the-art security layer for your PHP based web application. The IDS neither strips, sanitizes nor filters any malicious input, it simply recognizes when an attacker tries to break your site and reacts in exactly the way you want it to. Currently the PHPIDS detects all sorts of XSS, SQL Injection, header injection, directory traversal, RFE/LFI, DoS and LDAP attacks. Based on a set of approved and heavily tested filter rules any attack is given a numerical impact rating which makes it easy to decide what kind of action should follow the hacking attempt. This could range from simple logging to sending out an emergency mail to the development team, displaying a warning message for the attacker or even ending the user’s session.

PhpSecInfo provides an equivalent to the phpinfo() function that reports security information about the PHP environment, and offers suggestions for improvement. It is not a replacement for secure development techniques, and does not do any kind of code or app auditing, but can be a useful tool in a multilayered security approach.

Setup

A graphical frontend to PHP’s php.ini file, where all of the configuration of PHP takes place. The end result is that you can spend more time on your PHP code and less on tweaking ini file. It supports all of the standard PHP functionality, and has a special tab to handle any 3rd party plugins.

Lighty2Go is a, portable LightTPD, MySQL & PHP (LiMP) stack on a stick for Windows. Take it with you on your USB thumdrive and have some fun.

Personal AMP – Apache, MySQL and PHP – stack for the S60 mobile phone.

Allows you to setup Apache, PHP and the MySQL database on Windows. It also comes with PHPMyAdmin to easily manage your databases. WampServer allows you to add as many Apache, MySQL and PHP releases as you want.

A Webserver that runs out of the box without any installation and on write protected media. This means that web applications based on Server2Go can be used directly from CD ROM, a USB stick or from any folder on a hard disk without the hassle of configuring Apache, PHP or MySQL.

Testing

PHPUnit is a member of the  xUnit family of testing frameworks and provides both a framework that makes the writing of tests easy as well as the functionality to easily run the tests and analyze their results.

SimpleTest is is similar to JUnit/PHPUnit. It supports mock objects and can be used to automate the regression testing of web applications with a scriptable HTTP Client that can parse HTML pages and simulate things like clicking on links and submitting forms.

vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system. It can be used with any unit test framework, like PHPUnit or SimpleTest.

Cheet Sheets

The PHP cheat sheet is a one-page reference sheet, listing date format arguments, regular expression syntax and common functions.

Covering Type: Boolean, Integer, String, Array, Object/Class; String: functions, conversion; Array: functions, conversion;  Class: definition, member declaration, member visibility; Date/Time: functions, formats; Predefined Variables: $_SERVER$_FILES

Includes quick reference to CakePHP Config variables, Global Functions, Conventions, Paths and index.php file. It also provides reference for Properties, Methods & Callback functions for Models, View, Controller and Helper classes.

A table of keys that are defined in PHP’s $_SERVER superglobal array running on Apache and IIS servers. The purpose of this table is to allow PHP developers an insight of what to expect if they must migrate from one platform to another.

Anyone still interested in Smarty can use this cheat sheet. Contains quick tips and reference for Smarty template designers.

Handy PHP Code Snippets

1. Human Readable Random String

This code will create a human readable string that will look more close to dictionary words, useful for captchas.
view plaincopy to clipboardprint?

/**************
*@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;
}

2. Generate a Random String

If you don’t need human readable string, then use this function instead, which will create a random string you can use for user id’s etc.
view plaincopy to clipboardprint?

/*************
*@l – length of random string
*/
function generate_rand($l){
$c= “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789”;
srand((double)microtime()*1000000);
for($i=0; $i<$l; $i++) {
$rand.= $c[rand()%strlen($c)];
}
return $rand;
}

3. Encode Email Address

With this snippet, you can encode any email address into HTML entities so that spam bots do not find it.
view plaincopy to clipboardprint?

function encode_email($email=’info@domain.com’, $linkText=’Contact Us’, $attrs =’class=”emailencoder”‘ )
{
// remplazar aroba y puntos
$email = str_replace(‘@’, ‘@’, $email);
$email = str_replace(‘.’, ‘.’, $email);
$email = str_split($email, 5);

$linkText = str_replace(‘@’, ‘@’, $linkText);
$linkText = str_replace(‘.’, ‘.’, $linkText);
$linkText = str_split($linkText, 5);

$part1 = ‘<a href=”ma’;
$part2 = ‘ilto:’;
$part3 = ‘” ‘. $attrs .’ >’;
$part4 = ‘</a>’;

$encoded = ‘<script type=”text/javascript”>’;
$encoded .= “document.write(‘$part1’);”;
$encoded .= “document.write(‘$part2’);”;
foreach($email as $e)
{
$encoded .= “document.write(‘$e’);”;
}
$encoded .= “document.write(‘$part3’);”;
foreach($linkText as $l)
{
$encoded .= “document.write(‘$l’);”;
}
$encoded .= “document.write(‘$part4’);”;
$encoded .= ‘</script>’;

return $encoded;
}

4. Validate email Address

E-mail validation is perhaps the most used validation in web forms, this code will validate email address and also optionally check the MX records of the domain provided in email address to make email validation more robust.
view plaincopy to clipboardprint?

function is_valid_email($email, $test_mx = false)
{
if(eregi(“^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$”, $email))
if($test_mx)
{
list($username, $domain) = split(“@”, $email);
return getmxrr($domain, $mxrecords);
}
else
return true;
else
return false;
}

5. List Directory Contents

view plaincopy to clipboardprint?

function list_files($dir)
{
if(is_dir($dir))
{
if($handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if($file != “.” && $file != “..” && $file != “Thumbs.db”)
{
echo ‘<a target=”_blank” href=”‘.$dir.$file.'”>’.$file.'</a><br>’.”\n”;
}
}
closedir($handle);
}
}
}

6. Destroy Directory

Delete a directory including its contents.
view plaincopy to clipboardprint?

/*****
*@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;
}
}

7. Parse JSON Data

With most of the popular web services like Twitter providing their data through APIs, it is always helpful to know how to parse API data which is sent in various formats including JSON, XML etc.

$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

8. 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 />’;
}

9. Create Post Slugs

Create user friendly post slugs from title string to use within URLs.

function create_slug($string){
$slug=preg_replace(‘/[^A-Za-z0-9-]+/’, ‘-‘, $string);
return $slug;
}

10. Get Real IP Address of Client

This function will fetch the real IP address of the user even if he is behind a proxy server.

function getRealIpAddr()
{
if (!empty($_SERVER[‘HTTP_CLIENT_IP’]))
{
$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;
}


11. Force file Download

Provide files to the user by forcing them to download.

/********************
*@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”;
}
}

12. Creating a Tag Cloud

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’
. ‘” 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);

13. Find Similarity Between Two Strings

PHP includes a function similar_text very rarely used but quite useful that compares two strings and returns the percentage of similarity between two.

similar_text($string1, $string2, $percent);
//$percent will have the percentage of similarity

14. Use Gravatars in Your Application

With ever increasing popularity of WordPress, Gravatars have become quite popular. It is very easy to integrate them into your application as they provide a very easy to use API.

/******************
*@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=&#8217;.md5($email).
‘&default=’.$default.’&size=’.$size.’&rating=’.$rating.'” width=”‘.$size.’px”
height=”‘.$size.’px” />’;
}

15. Truncate Text at Word Break

This function will truncate strings only at word breaks which can be used to show a teaser for complete article without breaking words.

// Original PHP code by Chirp Internet: http://www.chirp.com.au
// Please acknowledge use of this code by including this header.
function myTruncate($string, $limit, $break=”.”, $pad=”…”) {
// return with no change if string is shorter than $limit
if(strlen($string) <= $limit)
return $string;

// is $break present between $limit and the end of the string?
if(false !== ($breakpoint = strpos($string, $break, $limit))) {
if($breakpoint < strlen($string) – 1) {
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return $string;
}

/***** Example ****/
$short_string=myTruncate($long_string, 100, ‘ ‘);

16. Zip Files on the Fly

/* 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);

Source: David Walsh

17. Unzip Zip File

/**********************
*@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’;
}

18. Prepend http to a URL

Some times you need to accept some url as input but users seldom add http:// to it, this code will add http:// to the URL if it’s not there.

if (!preg_match(“/^(http|ftp):/”, $_POST[‘url’])) {
$_POST[‘url’] = ‘http://&#8217;.$_POST[‘url’];
}

19. Convert URLs within String into hyperlinks

This function converts URLs and e-mail addresses within a string into clickable hyperlinks.

function makeClickableLinks($text) {
$text = eregi_replace(‘(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)’,
‘<a href=”\1″>\1</a>’, $text);
$text = eregi_replace(‘([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)’,
‘\1<a href=”http://\2″>\2</a>’, $text);
$text = eregi_replace(‘([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})’,
‘<a href=”mailto:\1″>\1</a>’, $text);

return $text;
}

20. Resize Images on the fly

Creating thumbnails of the images is required many a times, this code will be useful to know about the logic of thumbnail generation.

/**********************
*@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;
}

21. Detect AJAX Request

Most of the JavaScript frameworks like jQuery, mootools send and additional HTTP_X_REQUESTED_WITH header when they make an AJAX request, so that you can detect AJAX request on server side.(source)

if(!empty($_SERVER[‘HTTP_X_REQUESTED_WITH’]) && strtolower($_SERVER[‘HTTP_X_REQUESTED_WITH’]) == ‘xmlhttprequest’){
//If AJAX Request Then
}else{
//something else
}

21 Really Useful & Handy PHP Code Snippets

1. Human Readable Random String

This code will create a human readable string that will look more close to dictionary words, useful for captchas.
view plaincopy to clipboardprint?

/**************
*@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;
}

2. Generate a Random String

If you don’t need human readable string, then use this function instead, which will create a random string you can use for user id’s etc.
view plaincopy to clipboardprint?

/*************
*@l – length of random string
*/
function generate_rand($l){
$c= “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″;
srand((double)microtime()*1000000);
for($i=0; $i<$l; $i++) {
$rand.= $c[rand()%strlen($c)];
}
return $rand;
}

3. Encode Email Address

With this snippet, you can encode any email address into HTML entities so that spam bots do not find it.
view plaincopy to clipboardprint?

function encode_email($email=’info@domain.com’, $linkText=’Contact Us’, $attrs =’class=”emailencoder”‘ )
{
// remplazar aroba y puntos
$email = str_replace(‘@’, ‘@’, $email);
$email = str_replace(‘.’, ‘.’, $email);
$email = str_split($email, 5);

$linkText = str_replace(‘@’, ‘@’, $linkText);
$linkText = str_replace(‘.’, ‘.’, $linkText);
$linkText = str_split($linkText, 5);

$part1 = ‘<a href=”ma’;
$part2 = ‘ilto:’;
$part3 = ‘” ‘. $attrs .’ >’;
$part4 = ‘</a>’;

$encoded = ‘<script type=”text/javascript”>’;
$encoded .= “document.write(‘$part1’);”;
$encoded .= “document.write(‘$part2’);”;
foreach($email as $e)
{
$encoded .= “document.write(‘$e’);”;
}
$encoded .= “document.write(‘$part3’);”;
foreach($linkText as $l)
{
$encoded .= “document.write(‘$l’);”;
}
$encoded .= “document.write(‘$part4’);”;
$encoded .= ‘</script>’;

return $encoded;
}

4. Validate email Address

E-mail validation is perhaps the most used validation in web forms, this code will validate email address and also optionally check the MX records of the domain provided in email address to make email validation more robust.
view plaincopy to clipboardprint?

function is_valid_email($email, $test_mx = false)
{
if(eregi(“^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$”, $email))
if($test_mx)
{
list($username, $domain) = split(“@”, $email);
return getmxrr($domain, $mxrecords);
}
else
return true;
else
return false;
}

5. List Directory Contents

view plaincopy to clipboardprint?

function list_files($dir)
{
if(is_dir($dir))
{
if($handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if($file != “.” && $file != “..” && $file != “Thumbs.db”)
{
echo ‘<a target=”_blank” href=”‘.$dir.$file.'”>’.$file.'</a><br>’.”\n”;
}
}
closedir($handle);
}
}
}

6. Destroy Directory

Delete a directory including its contents.
view plaincopy to clipboardprint?

/*****
*@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;
}
}

7. Parse JSON Data

With most of the popular web services like Twitter providing their data through APIs, it is always helpful to know how to parse API data which is sent in various formats including JSON, XML etc.

$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

8. 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 />’;
}

9. Create Post Slugs

Create user friendly post slugs from title string to use within URLs.

function create_slug($string){
$slug=preg_replace(‘/[^A-Za-z0-9-]+/’, ‘-‘, $string);
return $slug;
}

10. Get Real IP Address of Client

This function will fetch the real IP address of the user even if he is behind a proxy server.

function getRealIpAddr()
{
if (!empty($_SERVER[‘HTTP_CLIENT_IP’]))
{
$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;
}

11. Force file Download

Provide files to the user by forcing them to download.

/********************
*@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”;
}
}

12. Creating a Tag Cloud

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);

13. Find Similarity Between Two Strings

PHP includes a function similar_text very rarely used but quite useful that compares two strings and returns the percentage of similarity between two.

similar_text($string1, $string2, $percent);
//$percent will have the percentage of similarity

14. Use Gravatars in Your Application

With ever increasing popularity of WordPress, Gravatars have become quite popular. It is very easy to integrate them into your application as they provide a very easy to use API.

/******************
*@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=&#8217;.md5($email).
‘&default=’.$default.’&size=’.$size.’&rating=’.$rating.'” width=”‘.$size.’px”
height=”‘.$size.’px” />’;
}

15. Truncate Text at Word Break

This function will truncate strings only at word breaks which can be used to show a teaser for complete article without breaking words.

// Original PHP code by Chirp Internet: http://www.chirp.com.au
// Please acknowledge use of this code by including this header.
function myTruncate($string, $limit, $break=”.”, $pad=”…”) {
// return with no change if string is shorter than $limit
if(strlen($string) <= $limit)
return $string;

// is $break present between $limit and the end of the string?
if(false !== ($breakpoint = strpos($string, $break, $limit))) {
if($breakpoint < strlen($string) – 1) {
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return $string;
}

/***** Example ****/
$short_string=myTruncate($long_string, 100, ‘ ‘);

16. Zip Files on the Fly

/* 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);

Source: David Walsh
17. Unzip Zip File

/**********************
*@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’;
}

18. Prepend http to a URL

Some times you need to accept some url as input but users seldom add http:// to it, this code will add http:// to the URL if it’s not there.

if (!preg_match(“/^(http|ftp):/”, $_POST[‘url’])) {
$_POST[‘url’] = ‘http://&#8217;.$_POST[‘url’];
}

19. Convert URLs within String into hyperlinks

This function converts URLs and e-mail addresses within a string into clickable hyperlinks.

function makeClickableLinks($text) {
$text = eregi_replace(‘(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)’,
‘<a href=”\1″>\1</a>’, $text);
$text = eregi_replace(‘([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)’,
‘\1<a href=”http://\2″>\2</a>’, $text);
$text = eregi_replace(‘([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})’,
‘<a href=”mailto:\1″>\1</a>’, $text);

return $text;
}

20. Resize Images on the fly

Creating thumbnails of the images is required many a times, this code will be useful to know about the logic of thumbnail generation.

/**********************
*@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;
}

21. Detect AJAX Request

Most of the JavaScript frameworks like jQuery, mootools send and additional HTTP_X_REQUESTED_WITH header when they make an AJAX request, so that you can detect AJAX request on server side.(source)

if(!empty($_SERVER[‘HTTP_X_REQUESTED_WITH’]) && strtolower($_SERVER[‘HTTP_X_REQUESTED_WITH’]) == ‘xmlhttprequest’){
//If AJAX Request Then
}else{
//something else
}

Create Stored Procedure in PHPMyAdmin

Creating stored procedure in the phpmyadmin is little bit different as we are creating using mysql IDE.

This is the method how we can create a stored procedure in PHPMYADMIN also,

delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;

By executing this will get successful new stored procedure created in your database as we are doing with SQLYOG or some IDE.

memcached

What is memcached?

memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use
in speeding up dynamic web applications by alleviating database load.

How it Works?

First, you start up the memcached daemon on as many spare machines as you have. The daemon has no configuration file, just a few command line options, only 3 or 4 of which you’ll likely use:

# ./memcached -d -m 2048 -l 10.0.0.40 -p 11211

This starts memcached up as a daemon, using 2GB of memory, and listening on IP 10.0.0.40, port 11211. Because a 32-bit process can only address 4GB of virtual memory (usually significantly less, depending on your operating system), if you have a 32-bit server with 4-64GB of memory using PAE you can just run multiple processes on the machine, each using 2 or 3GB of memory.

How to install ?

The folowing steps involved in installing the memcached,

1. Download memcache from code.jellycan.com/memcached/ [grab the ‘win32 binary’ version]

2. Install memcache as a service:
* Unzip and copy the binaries to your desired directory (eg. c:\memcached) [you should see one file, memcached.exe] – thanks to Stephen for the heads up on the new version
* If you’re running Vista, right click on memcached.exe and click Properties. Click the Compatibility tab. Near the bottom you’ll see Privilege Level, check “Run this program as an administrator”.
* Install the service using the command: c:\memcached\memcached.exe -d install from the command line
* Start the server from the Microsoft Management Console or by running one of the following commands: c:\memcached\memcached.exe -d start, or net start “memcached Server”

Now that you have memcache installed, you’ll have to tie it in with PHP in order to use it.

1. Check your php extensions directory [should be something like: C:\php\ext] for php_memcache.dll
If you don’t have any luck finding it, try looking at one of these sites:
– downloads.php.net/pierre/ [thanks to Henrik Gemal]
– pecl4win.php.net/ext.php/php_memcache.dll [currently down]
http://www.pureformsolutions.com/pureform.wordpress.com/2008/06/17/php_memcache.dll for PHP 5.2.*
– kromann.info/download.php?strFolder=php5_1-Release_TS&strIndex=PHP5_1 for PHP 5.1.* [thanks, Rich]

2. Now find your php.ini file [default location for XP Pro is C:\WINDOWS\php.ini] and add this line to the extensions list:

extension=php_memcache.dll

3. Restart apache

4. Run this code to test the installation: [found on http://www.php.net/memcache%5D

<?php
$memcache = new Memcache;
$memcache->connect(“localhost”,11211); # You might need to set “localhost” to “127.0.0.1”

echo “Server’s version: ” . $memcache->getVersion() . “<br />\n”;

$tmp_object = new stdClass;
$tmp_object->str_attr = “test”;
$tmp_object->int_attr = 123;

$memcache->set(“key”,$tmp_object,false,10);
echo “Store data in the cache (data will expire in 10 seconds)<br />\n”;

echo “Data from the cache:<br />\n”;
var_dump($memcache->get(“key”));
?>

If you see anything but errors, you are now using memcache!

EDIT the memcached setting:

Memcached, by default, loads with 64mb of memory for it’s use which is low for most applications. To change this to something else, navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\memcached Server in your registry, find the ImagePath entry and change it to look something like this:

“C:\memcached\memcached.exe” -d runservice -m 512

Now when you start the service via net start “memcached Server”, it will run with 512mb of memory at it’s disposal.

Dynamic Binding

In object oriented programming, dynamic binding means determining the exact implementation of a request based on both the request (operation) name and the receiving object at the run-time. It often happens when invoking a derived class’s member function using a pointer to its super class. The implementation of the derived class will be invoked instead of that of the super class. It allows substituting a particular implementation using the same interface and enables polymorphism.

Suppose all life-forms are mortal. In object oriented programming, we can say that the Person and Plant classes must implement the Mortal interface, which contains the method die().

Persons and Plants die in different ways; for example, Plants do not have hearts that stop. Dynamic binding is the practice of figuring out which method to invoke at runtime. For example, if we write

void kill(Mortal m) {
m.die();
}

it’s not clear whether m is a Person or a Plant, and thus whether Plant.die() or Person.die() should be invoked on the object. With dynamic binding, the m object is examined at runtime, and the method corresponding to its actual class is invoked.

15 PHP Regular Expression

Basically, a regular expression is a pattern describing a certain amount of text. Their name comes from the mathematical theory on which they are based.

Regular expressions syntax:
foo     —  The string “foo”
^foo     — “foo” at the start of a string
foo$     — “foo” at the end of a string
^foo$  —  “foo” when it is alone on a string
[abc]    —  a, b, or c
[a-z]     —  Any lowercase letter
[^A-Z]  — Any character that is not a uppercase letter
(gif|jpg)  —  Matches either “gif” or “jpeg”
[a-z]+    —  One or more lowercase letters
[0-9.-]    — Аny number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$    —  Any word of at least one letter, number or _
([wx])([yz])     — wy, wz, xy, or xz
[^A-Za-z0-9]     — Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4})   —  Matches three letters or four numbers

Function:

preg_match()  —   The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
preg_match_all() — The preg_match_all() function matches all occurrences of pattern in string.
preg_replace()  —    The preg_replace() function operates just like ereg_replace()  — except that regular expressions can be used in the pattern and replacement input parameters.
preg_split()  —   The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
preg_grep()  —  The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.
preg_ quote() —    Quote regular expression characters

1.Validate domain name

Verify if a string is a valid domain name.

$url = “http://komunitasweb.com/&#8221;;
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.”;
}

2.Enlight a word from a text

This very useful regular expression find a specific word in a text, and enlight it. Extremely useful for search results.

$text = “Sample sentence from KomunitasWeb, regex has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor”;
$text = preg_replace(“/b(regex)b/i”, ‘<span style=”background:#5fc9f6″>1</span>’, $text);
echo $text;

3.Enlight search results in your WordPress blog

As I just said that the previous code snippet could be very handy on search results, here is a great way to implement it on a WordPress blog.
Open your search.php file and find the the_title() function. Replace it with the following:

echo $title;

Now, just before the modified line, add this code:

<?php
$title     = get_the_title();
$keys= explode(” “,$s);
$title     = preg_replace(‘/(‘.implode(‘|’, $keys) .’)/iu’,
‘<strong></strong>’,
$title);
?>

Save the search.php file and open style.css. Append the following line to it:

strong.search-excerpt { background: yellow; }

4.Get all images from a HTML document

If you ever widhed to be able to get all images form a webpage, this code is a must have for you. You should easily create an image downloader using the power of cURL.

$images = array();
preg_match_all(‘/(img|src)=(“|’)[^”‘>]+/i’, $data, $media);
unset($data);
$data=preg_replace(‘/(img|src)(“|’|=”|=’)(.*)/i’,”$3”,$media[0]);
foreach($data as $url)
{
$info = pathinfo($url);
if (isset($info[‘extension’]))
{
if (($info[‘extension’] == ‘jpg’) ||
($info[‘extension’] == ‘jpeg’) ||
($info[‘extension’] == ‘gif’) ||
($info[‘extension’] == ‘png’))
array_push($images, $url);
}
}

5. Remove repeated words (case insensitive)

Often repeating words while typing? This handy regexp will be very helpful.

$text = preg_replace(“/s(w+s)1/i”, “$1”, $text);

6. Remove repeated punctuation

Same as above, but with punctuation. Goodbye repeated commas!

$text = preg_replace(“/.+/i”, “.”, $text);

7. Matching a XML/HTML tag

This simple function takes two arguments: The first is the tag you’d like to match, and the second is the variable containing the XML or HTML. Once again, this can be very powerful used along with cURL.

function get_tag( $tag, $xml ) {
$tag = preg_quote($tag);
preg_match_all(‘{<‘.$tag.'[^>]*>(.*?)</’.$tag.’>.’}’,
$xml,
$matches,
PREG_PATTERN_ORDER);

return $matches[1];
}

8. Matching an XHTML/XML tag with a certain attribute value

This function is very similar to the previous one, but it allow you to match a tag having a specific attribute. For example, you could easily match <div id=”header”>.

function get_tag( $attr, $value, $xml, $tag=null ) {
if( is_null($tag) )
$tag = ‘\w+’;
else
$tag = preg_quote($tag);

$attr = preg_quote($attr);
$value = preg_quote($value);

$tag_regex = “/<(“.$tag.”)[^>]*$attr\s*=\s*”.
“([‘\”])$value\\2[^>]*>(.*?)<\/\\1>/”

preg_match_all($tag_regex,
$xml,
$matches,
PREG_PATTERN_ORDER);

return $matches[3];
}

9. Matching hexadecimal color values

Another interesting tool for web developers! It allows you to match/validate a hexadecimal color value.

$string = “#555555”;
if (preg_match(‘/^#(?:(?:[a-fd]{3}){1,2})$/i’, $string)) {
echo “example 6 successful.”;
}

10. Find page title

This handy code snippet will find and print the text within the <title> and </title> tags of a html page.

$fp = fopen(“http://www.catswhocode.com/blog&#8221;,”r”);
while (!feof($fp) ){
$page .= fgets($fp, 4096);
}

$titre = eregi(“<title>(.*)</title>”,$page,$regs);
echo $regs[1];
fclose($fp);

12. Checking password complexity

This regular expression will tests if the input consists of 6 or more letters, digits, underscores and hyphens.
The input must contain at least one upper case letter, one lower case letter and one digit.

‘A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])[-_a-zA-Z0-9]{6,}z’

13. WordPress: Using regexp to retrieve images from post

As I know many of you are WordPress users, you’ll probably enjoy that code which allow you to retrieve all images from post content and display it.
To use this code on your blog, simply paste the following code on one of your theme files.

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

<?php
$szPostContent = $post->post_content;
$szSearchPattern = ‘~<img [^>]* />~’;

// Run preg_match_all to grab all the images and save the results in $aPics
preg_match_all( $szSearchPattern, $szPostContent, $aPics );

// Check to see if we have at least 1 image
$iNumberOfPics = count($aPics[0]);

if ( $iNumberOfPics > 0 ) {
// Now here you would do whatever you need to do with the images
// For this example the images are just displayed
for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
echo $aPics[0][$i];
};
};

endwhile;
endif;
?>

14. Generating automatic smileys

Another function used by WordPress, this one allow you to automatically replace a smiley symbol by an image.

$texte=’A text with a smiley :-)’;
echo str_replace(‘:-)’,'<img src=”smileys/souriant.png”>’,$texte);

15. Parsing Apache logs

Most websites are running on the well-known Apache webserver. If your website does, what about using PHP and some regular expressions to parse Apache logs?

//Logs: Apache web server
//Successful hits to HTML files only.  Useful for counting the number of page views.
‘^((?#client IP or domain name)S+)s+((?#basic authentication)S+s+S+)s+[((?#date and time)[^]]+)]s+”(?:GET|POST|HEAD) ((?#file)/[^ ?”]+?.html?)??((?#parameters)[^ ?”]+)? HTTP/[0-9.]+”s+(?#status code)200s+((?#bytes transferred)[-0-9]+)s+”((?#referrer)[^”]*)”s+”((?#user agent)[^”]*)”$’

//Logs: Apache web server
//404 errors only
‘^((?#client IP or domain name)S+)s+((?#basic authentication)S+s+S+)s+[((?#date and time)[^]]+)]s+”(?:GET|POST|HEAD) ((?#file)[^ ?”]+)??((?#parameters)[^ ?”]+)? HTTP/[0-9.]+”s+(?#status code)404s+((?#bytes transferred)[-0-9]+)s+”((?#referrer)[^”]*)”s+”((?#user agent)[^”]*)”$’

Replacing double quotes by smart qutotes

If you’re a typographer lover, you’ll probably love this regexp, which allow you to replace normal double quotes by smart quotes. A regular expression of that kind is used by WordPress on contents.

preg_replace(‘B”b([^”x84x93x94rn]+)b”B’, ‘?1?’, $text);

Will_paginate Customization

Will_paginate will give the neatful form of pagination as seen in the earlier. Here we can see the
the some customized form displaying the pagination displays,

<%= will_paginate @display_data %>

— will  display the normal pagination navigation icon as seen.

<%= will_paginate @display_data, :page_links => false %>

— will  display the normal previous and Next icon exlcuding the page numbers.

Find Record/Information Time Line

In Rails, we can find the last updated record date/time information with the current date/time information. This can be done as seen below,

def self.didwhen(old_time)
val = Time.now – old_time
if val < 10 then
result = ‘just a moment ago’
elsif val < 40  then
result = ‘less than ‘ + (val * 1.5).to_i.to_s.slice(0,1) + ‘0 seconds ago’
elsif val < 60 then
result = ‘less than a minute ago’
elsif val < 60 * 1.3  then
result = “1 minute ago”
elsif val < 60 * 50  then
result = “#{(val / 60).to_i} minutes ago”
elsif val < 60  * 60  * 1.4 then
result = ‘about 1 hour ago’
elsif val < 60  * 60 * (24 / 1.02) then
result = “about #{(val / 60 / 60 * 1.02).to_i} hours ago”
else
result =old_time.strftime(“%H:%M %p %B %d, %Y”)
end
result
end

By passing the created_dt value to the above function from the rails view section to get printed.The synatax is like,

<% timenow1 = ModelName.didwhen(tablename.created_at)    %>

Customized URL-Rewriting

In my rails application, i did custom URL rewrite since then my project navigation will look like this,

http://localhost:3000/   — redirecting to index page
http://localhost:3000/home
http://localhost:3000/profile

For doing this you have to write  the map condition in your rails rout.rb files. The will be like this,

As in my application just want to show simplified custom url as above for that in the route.rb i wrote like this,

map.home ‘/home’,:controller=>”signup”, :action=>”update”

map.profile ‘/profile’,:controller=>”signup”, :action=>”profile”

In my view section for those  navigation, i.e link_to tage look like this,

<%= link_to “Home” , {:controller => “signup”, :action => “signup”} %>

<%= link_to “Profile” , {:controller => “signup”, :action => “profile”} %>

That’s all to get the desired Custom URL.

Note:

For more info on URL rewrite can get here :
http://guides.rails.info/routing.html

Rails Booklet

Here is the quick guide to know the basic of Ruby on Rails. Please click the link to download,

Ruby on Rails Book-Let

« Older entries