Case Sensitive Issue – Magento Products

While shifting the your magento site which is hosted in the Windows server to the Linux server you will see strange thing is that the actual product images are not get dispalyed instead magento default product images
appear in all the product.

This problem has discussed in magento forum a lot. I have to thanks Mr.Chris Jones.

How to fix this ? ….. 🙂

Below is the solution is given by the Mr. Chris Jones in Mangeto Forum

<?php

fix_magento_catalog(“/yourmagentoinstall/media/catalog/product”, “mysql_host”, “mysql_user”, “mysq_password”,
“mysql_db”);

function list_files_and_folders($path=”.”)
{
$files = array();
if (is_dir($path))
{
$fh = opendir($path);
while (($file = readdir($fh)) !== false)
{
if (strcmp($file, “.”)==0 || strcmp($file, “..”)==0) continue;
$filepath = $path . “/” . $file;
if ( is_dir($filepath) )
{
array_push($files, $filepath);
$files = array_merge($files, list_files_and_folders($filepath));
}
else
{
array_push($files, $filepath);
}
}
closedir($fh);
}
else
{
$files = false;
}
return $files;
}

function fix_magento_catalog($path, $mysql_host, $mysql_username, $mysql_password, $mysql_db)
{
$files = list_files_and_folders($path);
foreach ($files as $val)
{
echo “Converting {$val} to”.strtolower($val).” \n”;
rename($val, strtolower($val));
}

$conn = mysql_connect($mysql_host,$mysql_username,$mysql_password);
mysql_select_db($mysql_db);

$query = mysql_query(“select value_id, value from catalog_product_entity_media_gallery”) or die(mysql_error());

while($result = mysql_fetch_assoc($query)) {
echo “Converting database value {$result[‘value_id’]} to “.strtolower($result[‘value’]).” \n”;
mysql_query(“update catalog_product_entity_media_gallery set value='”.strtolower($result[‘value’]).”‘ where value_id='{$result[‘value_id’]}'”) or die(mysql_error());
}
}
?>

In the above code, we are renaming the media/catalog/product subfolders and the files to lowercase and also the changing the the url image path to the loweecase in the following table is must.

  • catalog_product_entity_media_gallery
  • catalog_product_entity_varchar
  • catalog_product_flat_1
  • catalog_product_flat_2
  • catalog_product_flat_3
  • catalog_product_flat_4
  • catalog_product_flat_5
  • catalog_product_flat_6
  • catalog_product_flat_7
  • catalog_product_flat_8
  • catalog_product_flat_9

Note:
Above code, the Database update query part is done only for catalog_product_entity_media_gallery table so we have
to do update for other 10 tables.

Useful Classes And Libraries For PHP Developers

Numerous PHP Frameworks have evolved to enable rapid web development with PHP. However even greater number of standalone PHP libraries and classes are available which provide similar benefits. W3Avenue has compiled a list of some really useful classes and libraries that every PHP developers should be familiar with. Whether you like to use a PHP Framework or prefer to work without one, your productivity can multiply with the help of these libraries and classes.

Database

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.

A set of PHP classes mimicing C#3.0’s LINQ (Language Integrated Query) extension methods.PHPLinq currently features: LINQ operators (select, take, skip, orderBy / orderByDescending, thenBy / thenByDescending), Lambda expressions, and Anonymous types.

Mimesis is an Open Source PHP Flat File Database low-level API designed to act as a backend for server-side scripts that require database functionality. Instead of parsing SQL statements, Mimesis uses PHP’s object-oriented constructs to provide a distinct class with various database manipulation methods.

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.

Document

An Open Source PHP class for generating PDF documents. Requires no external libraries for the basic functions; supports all ISO page formats including UTF-8, Unicode, RTL languages and HTML.
* PHPPowerPoint-http://www.phppowerpoint.net/
Based on Microsoft’s OpenXML standard PHPPowerPoint Classes enables you to read and write PowerPoint files. Features include: setting presentation meta data (author, title, description, 
), adding slides, adding images to your presentation and much more!

Based on Microsoft’s OpenXML standard PHPExcel Class enables you to read and write Excel files. Features include:  setting spreadsheet meta data (author, title, description, 
), multiple worksheets, different fonts and font styles, cell borders, fills, gradients, adding images to your spreadsheet and much, much more!

Purpose of this library is to create RTF documents with PHP, which are compatible with Microsoft Word and Open Office Writer programs. Main features include: Document sections formatting: margins, paper size, borders and other (document can have more than one section); Headers and footer formatting; Paragraph control: background, borders, alignment and other; Font control: bold, italic, face, size, color (it’s possible to use html style tags); Embedded images (.jpg and .png formats); Tables formatting: sizes, borders, background and alignment of cells; UTF-8 support.

Offers compression and extraction functions for Zip formatted archives (WinZip, PKZIP). It gives you the ability to create an archive, list the content and extract all its content in the file system. PclZip defines an object class which represent a Zip Archive. This class manages the archive properties and offers access method and actions on the archive.

Email

Swift Mailer integrates into any web app written in PHP 5, offering a flexible and elegant object-oriented approach to sending emails with a multitude of features: Send emails using SMTP, Sendmail, Postfix or a custom Transport implementation of your own, Support servers that require username & password and/or encryption, Protect from header injection attacks without stripping request data content, Send MIME compliant HTML/multipart emails, Use event-driven plugins to customize the library, Handle large attachments and inline/embedded images with low memory use.

Full featured email transfer class for PHP. PHPMailer features: Supports emails digitally signed with S/MIME encryption, Supports emails with multiple TOs, CCs, BCCs and REPLY-TOs, Supports Text & HTML emails, Embedded image support, Multipart/alternative emails for mail clients that do not read HTML email, Redundant SMTP servers, SMTP authentication, Tested on multiple SMTP servers: Sendmail, qmail, Postfix, Gmail, Imail, Exchange, etc.

Form

An open-source free PHP CAPTCHA script for generating complex images and CAPTCHA codes to protect forms from spam and abuse. It can be easily added into existing forms on your website to provide protection from spam bots.

phpObjectForms is a fully object-oriented, highly customizable, easily extendable, library for creating and processing HTML forms without writing any HTML code. Main Features: Support for all the standard HTML form input elements, Server-side input validation based on regular expressions, Optional client-side JavaScript pre-validation, Support for template-based forms. The output forms presentation is highly tied with CSS, therefore it can be easily tuned without writing any code but only by changing the style sheet.

HTML / CSS

HTML Purifier is a standards-compliant HTML filter library written in PHP. HTML Purifier will not only remove all malicious code (better known as XSS) with a thoroughly audited, secure yet permissive white list, it will also make sure your documents are standards compliant, something only achievable with a comprehensive knowledge of W3C’s specifications.

GeSHi is a syntax highlighter for HTML, written in PHP. Basically, you input the source you want to highlight and the name of the language you want to highlight it in, and GeSHi returns the syntax-highlighted result. But it doesn’t stop there – GeSHi has many powerful and unique features, including: The ability to change the styles of any highlighted element on the fly, Use of CSS classes to reduce the amount of output produced (GeSHi can also produce a stylesheet to be used with a language on the fly), XHTML 1.0 Strict + CSS2 compliance, Auto-caps/noncaps of keywords, Line numbering (both normal and fancy forms, see the demo, and many more!

Image / Media / File

A PHP image processing solution, with “pluggable” drivers(adapters) for virtually any environment: GD2, Magick Wand, Image Magick via shell, Image Magick via extension, etc. Asido offers the following functionality: resize images, watermark images, rotate imates, copy images, crop images, grayscale images, convert images.

A light-weight image manipulation library aimed at thumbnail generation. It features the ability to resize by width, height, and percentage, create custom crops, or square crops from the center, and rotate the image. You can also easily add custom functionality to the library through plugins. It also features the ability to perform multiple manipulations per instance (also known as chaining), without the need to save and re-initialize the class with every manipulation.

WideImage is an object-oriented library for image manipulation. The library focuses on often-used image operations and ease of use. It provides a simple and unified way to loading and saving images from/to files, strings, database and even URLs (load only, must be enabled in PHP). Supports the most common image formats: GIF, PNG, JPEG, GD and GD2.

Allows you to resize and crop any image on your website without touching the actual image or writing any code. Simply upload each image once at a high enough resolution and then reuse it at any size you want, anywhere you want. Features include: Resizes JPEGs, GIFs, and PNGs, Intelligently sharpens for crisp photos at any size, Can crop based on width:height ratios, Can color-fill transparent GIFs and PNGs, Built-in caching keeps image variations for optimal performance.

This PHP script uploads files and manipulates images very easily. The perfect script to generate thumbnails or create a photo gallery! It can convert, resize and work on uploaded images in many ways, add labels, watermarks and reflections and other image editing features. You can use it for files uploaded through an HTML form, a Flash uploader, or on local files.

A PHP script that extracts useful information (such as ID3 tags, bitrate, playtime, etc.) from MP3s & other multimedia file formats (Ogg, WMA, WMV, ASF, WAV, AVI, AAC, VQF, FLAC, MusePack, Real, QuickTime, Monkey’s Audio, MIDI and more).

JavaScript / AJAX

PHPLiveX is a lightweight PHP-JavaScript class library that helps you integrate AJAX to your PHP applications. Without a page is loaded again, you may call your PHP functions in the same page, submit your form to an URL and send a request to another page with any type of data.

Xajax is an open source PHP library and JavaScript engine that allows you to easily create powerful, web-based, Ajax applications using HTML, CSS, JavaScript, and PHP that can asynchronously call server-side PHP functions and update content.

Microformats

Extensible Microformats Parser for PHP 5. Currently supported Microformats include: xfn, rel-license, rel-tag, geo, adr, hcard, hcalendar, hreview, hresume.

iCalcreator is a PHP class managing iCal formatted files for non-calendar systems like CMS, project management systems and other applications able to process calendar information. iCalcreator features create, parse, edit and select calendar and calendar components.

A simple PHP5 tool for extracting common microformats from a page. The page can be presented as a string or a URL, and the result is handed back as a standard PHP array structure. hkit uses SimpleXML for parsing, and therefore requires PHP5.

A Simple set of XSLT and PHP tools for Transforming Microformats.

RSS & Atom Feeds

An open sources PHP class that provides an easy to use API for handling all of the dirty work when it comes to fetching, caching, parsing, normalizing data structures between RSS and Atom formats, handling character encoding translation, and sanitizing the resulting data.

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.

Testing & Debugging

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-http://simpletest.sourceforge.net/
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.

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.

Web Services

  • XML-RPC Library for PHP

a fully compliant XML-RPC client and server written in pure PHP. Only requirements are PHP, and the XML parser you’re guaranteed to have if you’re using PHP built into Apache (which most people are).

HTML ‘n’ Level Menu

Generating  HTML UL and LI ‘ ‘n’ level menu  in php can done as follows,

<?php
$stack = array();

$mysql = array();
$mysql[‘host’] = ‘localhost’;
$mysq[‘username’] = ‘username’;
$mysql[‘password’] = ‘password’;
$mysql[‘database’] = ‘dbname’;
$mysql[‘tbl_prefix’] = ”;

if(!$conn = mysql_pconnect($mysql[‘host’], $mysq[‘username’], $mysql[‘password’]))
{
echo “Error: Failed to connect MySQL”;
exit;
}
mysql_select_db( $mysql[‘database’], $conn);

$query=mysql_query(“select * from menus where parent_id=0 and active=1”);
echo “<div id=’myjquerymenu’ class=’jquerycssmenu’>”;
echo “<ul>”;
while($row = mysql_fetch_array($query))
{
//echo “<div id=’menu”.$row[‘id’].”‘ class=’dropmenudiv’>”;
$menuspath=”;
$arr = get_path($row[‘id’]);
for($j=0;$j<(sizeof($arr)-1);$j++)
{
$menuspath .= “/”.$arr[$j];
}
echo “<li class=’menu”.$row[‘id’].”‘><a href='”.$menuspath.”/”.$row[‘url’].”‘>”.$row[‘name’].”</a>”;
test($row[‘id’]);
//echo “</div>”;
echo “</li>”;
}
echo “</ul>”;
echo “</div>”;

function test($id)
{

$query1=mysql_query(“select * from menus where parent_id='”.$id.”‘ and active=1″);
$query3=mysql_fetch_array(mysql_query(“select * from menus where id='”.$id.”‘ and active=1″));
$parentmenuname = ”;
if(mysql_num_rows($query1)!=0)
{
//echo “<ul id=’verticalmenu’ class=’glossymenu’>”;
echo “<ul style=’border:1px solid #BDBDBC;’>”;
while($row1 = mysql_fetch_array($query1))
{

$menuspath=”;
$query4=mysql_fetch_array(mysql_query(“select * from menus where id='”.$row1[‘id’].”‘ and active=1″));
if($query4[‘parent_id’]!=0){

$arr = get_path($row1[‘id’]);
for($j=0;$j<(sizeof($arr)-1);$j++)
{
$menuspath .= “/”.$arr[$j];
}
}
echo “<li><a href='”.$menuspath.”/”.$row1[‘url’].”‘>”.$row1[‘name’].”</a>”;
$query2=mysql_query(“select * from menus where parent_id='”.$row1[‘id’].”‘”);

if(mysql_num_rows($query2)!=0)
{
//rootmenu($row1[‘id’]);

test($row1[‘id’]);
}
else
{
echo “</li>”;
}

}
echo “</ul>”;
}

}

function get_path($node) {
// look up the parent of this node
$result = mysql_query(‘SELECT parent_id,name FROM menus ‘.
‘WHERE id=”‘.$node.'”;’);
$row = mysql_fetch_array($result);

// save the path in this array
$path = array();

// only continue if this $node isn’t the root node
// (that’s the node with no parent)
if ($row[‘parent_id’]!=”) {
// the last part of the path to $node, is the name
// of the parent of $node
$path[] = $row[‘name’];

// we should add the path to the parent of this node
// to the path
$path = array_merge(get_path($row[‘parent_id’]), $path);
}

// return the path
return $path;
}
?>

The above code read the menu title from the menu tables to structure the UL and LI navigation as per our need. The Data Structure of the menu table will look like below,

DROP TABLE IF EXISTS `menus`;

CREATE TABLE `menus` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(255) default NULL,
`admin_id` int(10) default NULL,
`parent_id` int(10) default NULL,
`url` varchar(255) default NULL,
`order` int(10) default NULL,
`active` int(10) default NULL,
`default_item_id` int(10) default ‘0’,
`created` datetime default NULL,
`modified` datetime default NULL,
`created_from` int(10) NOT NULL default ‘0’,
`ismodifiedby` varchar(256) default NULL,
`iscreatedby` varchar(256) default NULL,
PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=96 DEFAULT CHARSET=latin1;

Import Data from Excel

Importing Data from the excel sheet can be done in php on following way,

<?php

require_once ‘reader.php’;

$filename=”test.xls”;
$prod=parseExcel($filename);
echo”

";
print_r($prod);
echo"

“;
function parseExcel($excel_file_name_with_path)
{
$data = new Spreadsheet_Excel_Reader();
// Set output Encoding.
$data->setOutputEncoding(‘CP1251’);
$data->read($excel_file_name_with_path);

$colname=array(‘id’,’name’);

for ($i = 1; $i <= $data->sheets[0][‘numRows’]; $i++) {
for ($j = 1; $j <= $data->sheets[0][‘numCols’]; $j++) {

$product[$i-1][$j-1]=$data->sheets[0][‘cells’][$i][$j];
$product[$i-1][$colname[$j-1]]=$data->sheets[0][‘cells’][$i][$j];
}
}
return $product;
}
?>

The above code, will read the content from the test.xls  and import to the string which can later on to upload in the table or just print the value.

Here ‘reader.php’ used as the library to read data from the excel, that can be download from the following url.

http://www.box.net/shared/zf9zip4v41

Export to Excel:

To export data from table to excel can done same as the above except adding this header to tell the php to content will redirect to excel.

header(“Content-type: application/octet-stream”);
header(“Content-Disposition: attachment; filename=test_list.xls”);
header(“Pragma: no-cache”);


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

« Older entries