Setting Vagrant with Yii PHP

vagrant

As everyone is talking about start using Vagrant, I’m writing this post about how you can use it for Yii and customize it for other projects written in PHP.

I’m not going to tell you why are we using Vagrant, bit far point less, if some of you is interested why we need it than please look at their offical site,
Here we just want a standard development environment every team developer can use and work with it.

Have a look at what we are going to do today! it will just take few minutes 🙂

1. Installing Vagrant
2. Installing VirtualBox
3. Setting up Vagrant with my favorite box
4. Provisioning with Vagrant
5. Setting up Apache, PHP 5.X, Mysql 5.X and othe things

last but not least we need a working copy of yii framework, where you are developing your app!

1. Installing Vagrant
I’m using Ubuntu 12, I’m not going to run through how to do this in every operating system because it is out of the scope of this tutorial.
So the first thing to do is to head over to the downloads page of Vagrant and install the version fits for your operating system.
Once fully installed, the command vagrant is now available to use in your favorite terminal.

2. Installing VirtualBox
Another requirement to use Vagrant is that you have a Virtual Machine provider. This is basically just software that runs the virtual machine. I’m going to be using VirtualBox because it’s free and easy to set up. After installation you don’t need to check as much. Lets proceed!

3. Setting up Vagrant with my favorite box
Now the fun part has arrived! Vagrant is basically just a configuration file (Vagrantfile) that tells the VirtualMachine what to set up and in the end what to run. The Vagrantfile should be kept in the root of your project and should be added to Git so that anyone else who is working on the project can use the same configuration file.
Lets open our favorite terminal and move to the working directory where your project is setup.

cd /var/www/project/stowitt/front-panel/

now do:

vagrant init

Now if you open your project in a text editor, you will see the new Vagrantfile into your project.

Next thing is your need is box. When you are setting up a Virtual Machine, you need the operating system and all of that junk before you even begin. Operating system is the Vagrant box here, Vagrant provides base images of those operating system.
To download an Ubuntu box, run the following command:

vagrant box add precise32 http://files.vagrantup.com/precise32.box

Once done add the following lines to your Vagrantfile:

config.vm.box = "base"
config.vm.box = "precise32"

Now it knows which box to use and your machine is just ready?? wanna try! run the command in terminal:

vagrant up

You should see a load of output to the terminal. Vagrant doesn’t actually have a user interface so you will see only the output of every command. Now to see what is going on you can do SSH, similar to your production environment.
While it’s up do:

vagrant ssh

You are not into the virtual machine! You can do anything you want but lets type “exit” and return for now.

After ended up working on machine, we can shut it down by using the following command:

vagrant destroy

Now lets do this back:

$ vagrant up
$ vagrant ssh
$ cd /vagrant
$ ls -l

You should see a list of all the files from your project. Vagrant will automatically sync all of the files from the root of the project. Pretty cool!

4. Provisioning with Vagrant

If you have ever set up a fresh installation of Ubuntu, you will know that you have to install a load of things before you are good to go. Now that you can SSH into your machine, you can happily go about installing whatever you want to set up the machine exactly how you want it.

To set up provisioning, all we have to do is to create a shell script that will automatically be loaded when we boot up Vagrant.

Create a new file called bootstrap.sh in the root of your project (the same location where you saved Vagrantfile).

Next we need to tell Vagrant to run this file when it starts up. Open your Vagrantfile and add the following line under where you set the box:

config.vm.box = "precise32"
config.vm.provision :shell, :path => "bootstrap.sh"

Now that we have provisioning set up, we can start adding a list of instructions for what should be provisioned whenever Vagrant is set up.

5. Setting up Apache, PHP 5.X, Mysql 5.X and othe things

Now we are ready to install anything we want on our virtual development machine. To be specific about PHP and specially Yii we are going to install these items one by one.

Open up your boostrap.sh file and add the following:

#!/usr/bin/env bash

Now lets update Ubuntu:

apt-get update

You need to add these lines in bootstrap.sh as we go!!!

Install Vim:

apt-get install -y vim

Set up Apache:

apt-get install -y apache2
# Remove /var/www default
rm -rf /var/www
# Symlink /vagrant to /var/www
ln -fs /vagrant /var/www
# Add ServerName to httpd.conf
echo "ServerName localhost" > /etc/apache2/httpd.conf
# Setup hosts file
VHOST=$(cat <<EOF
<VirtualHost *:80>
  DocumentRoot "/vagrant/public"
  ServerName localhost
  <Directory "/vagrant/public">
    AllowOverride All
  </Directory>
</VirtualHost>
EOF
)
echo "${VHOST}" > /etc/apache2/sites-enabled/000-default
# Enable mod_rewrite
a2enmod rewrite
# Restart apache
service apache2 restart

Install PHP 5.X:

apt-get install -y libapache2-mod-php5
apt-get install -y python-software-properties
add-apt-repository ppa:ondrej/php5
apt-get update

Set up other PHP stuff:

# Need sudo to run the following, adding root password as "Crazy007Fox"
sudo passwd
Crazy007Fox
sudo
Crazy007Fox
apt-get install -y php5-cli
apt-get install -y php5-mysql
apt-get install -y php5-curl
apt-get install -y php5-mcrypt

Install cURL:

apt-get install -y curl

Install MySQL:

export DEBIAN_FRONTEND=noninteractive
apt-get -q -y install mysql-server-5.5

Install Git:

apt-get install git-core

Set up Yii:

# setup database:
echo "CREATE DATABASE IF NOT EXISTS yii_app" | mysql
echo "CREATE USER 'root'@'localhost' IDENTIFIED BY ''" | mysql
echo "GRANT ALL PRIVILEGES ON yii_app.* TO 'yii_app'@'localhost' IDENTIFIED BY ''" | mysql
# run migration
cd /var/www/
yiic migrate
# give write permission to some directories
sudo chmod -R 777 /var/www/assets/
sudo chmod -R 777 /var/www/protected/runtime/

 

Final Run

Now everything got setup, but hey! how do I run the project from virtual machine. Well Vagrant makes this really easy with it’s port forwarding feature. This simply allows you to specify ports on the guest machine to share via a port on the host machine.

Add the following line to your Vagrantfile:

config.vm.network :forwarded_port, host: 8090, guest: 80

now start your machine with vagrant up
vagrant up

Once done, on your local machine try:

http://localhost:8090 in your browser to see your project.

Checkmate you are done with your virtual machine setup and your site is running 🙂

Advertisements

25 Tips to Optimize Your Code

Initially I had a chance to write code optimization techniques as a hunt of compiler construction in C++ and later I decided to do this specifically for web programing languages, as I have been working on Python, Perl and Ruby to figure out which language can be better to write applications that executes faster.
I personally found Python to be better in performance then PHP, Perl or Ruby. However If you are still a PHP developer or generally write web code these 25 tips can help you lot in terms of writing fast and memory efficient applications.

1. Upgrade Your Distribution
Simply upgrading your distribution like PHP, is without a doubt one of the easiest ways to improve PHP performance. In addition to the usual bug fixes and new features, each new PHP release ships with optimization improvements which can produce noticeable performance enhancements.

2. Use Native Functions
As much as possible, try to use native PHP functions rather than writing your own functions to achieve the objective. For example, you can use range( b, k) to get an array of alphabets starting from b to k in sequence, if it is only needed once in the script rather than declaring an array with these values in a function and returning it on its call.

3. Take Advantage of Native Extensions
PHP has long been accused of including everything but the kitchen sink, and in recent years the development team has made great strides in terms of stripping the core distribution of optional and redundant features (such as deprecating the redundant POSIX Regex library in preference of the PCRE library). Even so, the sheer number of available libraries and other extensions can be overwhelming, leading some developers to consider implementing their own solutions rather than invest the time investigating what’s already available.
For instance it might be tempting to spend a few hours writing a custom library capable of parsing XML, despite the availability of SimpleXML. Doing so ignores the many hours of troubleshooting and optimization already put into the native extensions, thereby almost guaranteeing the substandard outcome of any such custom solution. For this reason and others you should always investigate the availability of an existing library or extension before setting out to reinvent the wheel.

4. Use a PHP Accelerator
Barring outside interference, a PHP script executes after being “compiled” by the PHP engine, which turns the PHP code you’ve written into machine language, known as operation code (opcode). If the PHP script repeatedly churns out an identical result, then why not skip the compilation process altogether?
You can do exactly this using a PHP accelerator, which caches a PHP script’s compiled machine code, allowing the code to immediately execute upon request rather than after a potentially expensive compilation process.
Several opcode caching solutions are available to PHP developers, including notably APC (Alternative PHP Cache), an open source accelerator available for installation via PEAR. Another popular solution is Zend Server, which incorporates not only opcode caching, but also full and partial page caching utilities.

5. Use Late Static Binding
If a method can be static, declare it static. Speed improvement is by a factor of 4. As of PHP 5.3.0 Late static binding introduced, a new use for the static keyword, which addresses this particular shortcoming. When you use static, it represents the class where you first use it, ie. it ‘binds’ to the runtime class.
For example this will blow the code execution:

abstract class Builder {
    public static function build() {
        return new static;
    }
}
class Member extends Builder {
    public function who_am_i() {
        echo 'Member';
    }
}
Member::build()->who_am_i();

6. Performance of FOR vs FOREACH in PHP
My personal opinion is to use what makes sense in the context. Personally I almost never use for for array traversal. I use it for other types of iteration, but foreach is just too easy… The time difference is going to be minimal in most cases.
For some reasons I decided to do a quick benchmark run…

$a = array();
for ($i = 0; $i < 10000; $i++){
$a[] = $i;
}

$start = microtime(true);
foreach ($a as $k => $v){
$a[$k] = $v + 1;
}
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v){
$v = $v + 1;
}
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => $v) {}
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {}
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

And the results:
Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds

So if you’re modifying the array in the loop, it’s several times faster to use references…

7. Frequently Used Switch Cases
Keep most frequently used switch cases on the top. A switch statement is not always faster than an if statement. It scales better than a long list of if-else statements as switch can perform a lookup based on all the values. However, for a short condition it won’t be any faster and could be slower.

8. Conditions that uses = = =
Use “= = =” instead of “= =”, as the former strictly checks for a closed range which makes it faster.

9. Pass Reference to Function
Pass reference to the function if it does not affect your logic. A function manipulating the reference is faster than those manipulating the value been passed as here one more copy of the value is getting created. Especially it adds overhead when the value passed by you is a big array.
For example, let us create a function in two different way to increment by 1, each element of an array having values 0 to 99.

// passing by reference
function  computeValue( &$param )
{
// Something goes here
foreach( $param as $k => $value)
{
$param[$k] = $value + 1;
}
}
$x = array();
for( $i =0; $i<99; $i++)
{
$x[$i] = $i;
}
computeValue( $x);

// array with 100 elements each incremented by 1
print_r( $x );

The function above works faster than the function below although both will produce the same result ( increment each element of the array by 1. )

// passing by value
function  computeValue( $param )
{
// Something goes here
foreach( $param as $k => $value)
{
$param[$k] = $value + 1;
}
return $param;
}
$x = array();
for( $i =0; $i<99; $i++)
{
$x[$i] = $i;
}
// array with 100 elements each incremented by 1
print_r(computeValue( $x));

10.    Use Caching Techniques
Use cache to reduce the load of database operations as well as the script compilation. We can use memcache for the reducing database load and APC for opcode caching and intermediate code optimization.

11.    Use Single Quotes
Using single quotes ( ‘ ‘ ) is faster than using double quotes( ” ” ) if you are going to keep only the string inside it avoiding any variables. Double quotes checks for the presence of variable and adds little bit of overhead.

12.    Use Appropriate String Functions
str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4.

13.    Calculate Only Once
Calculate and assign the value to the variable if that value is getting used numerous time rather than calculating it again and again where it is being used.
For example, the following will degrade the performance.

for( $i=0; i< count($arrA); $i++)
{
echo count($arrA);
}

The script below will perform much better.

$len = count($arrA);
for( $i=0; i< $len; $i++)
{
echo $len;
}

 

14.    Disable Debugging Messages
File operations are a bit expensive if you are using it quite often in code. So, if you are calling lot of custom functions to log errors and warning during your development process, make sure you remove them before you push the code to production.

15.    Use Methods in Derived Classes
Methods in derived classes are faster than base classes. For example, let there be a function in both base class and derived class for performing task1. It is named as “forTask1? in base class and “forTask1again” in derived class, so that they will not override.
Call to the function “forTask1again( )” which is in derived class will work faster than call to the function “forTask1( )” as it is from base class.

class someBaseClass
{
public function forTask1($string)
{
// perform task 1
}
public function forTask2( )
{
// perform task 2
}
}

class derivedClass extends someBaseClass
{
public function forTask1again($string)
{
//perform task 1 same as the function in base class.
}
public function forTask3($string)
{
//perform task 3
}
}

//Instantiating the derived class below.
$objDerivedClass = new derivedClass( );

// The call below works slow for task1 as it is from base class.
$resultTask1 = $objDerivedClass->forTask1( );

// The call below works faster for task1 as
// it is from derived class.
$sameResultTask1 = $objDerivedClass->forTask1again();

 

16.    JSON Vs. XML
Use JSON instead of XML while working with web services as there are native php function like json_encode( ) and json_decode( ) which are very fast. If you are bound to have XML form of data, then use regular expression to parse it instead of DOM manipulation.

17.    Use isset
Use isset( ) where ever possible instead of using count( ), strlen( ), sizeof( ) to check whether the value returned is greater than 0.
For example, let us assume that you have a function which returns an array with values or a NULL array. Now you want to check whether the returned array is with values or not, then use the following:

if(isset($returnValue))
{
// do something here
}
In this case, use the above code block, instead of the following:
if(count($returnValue) > 0)
{
// do something here
}

 

This will also be fast to execute:

// Checking if string length is 5
if(isset($foo{5}))
{
}

18.    Pre increment vs Post increment
Well, increment a certain value also have a few ways to improve. We all know that there are many ways to increment integer values such as – See more at:

$i++;
$++i
$i+=1;
$i = $i + 1;

Out of all these what way is the most efficient? In PHP, it seems like pre increment is better than the other ways of performing an increment. Its around 10% better than post increment? The reason? Some said that post increment made certain copy unlike pre increment. There isn’t any benchmark done for PHP but i found one on C++ which should be quite the same. Well, without a proper benchmark on this, i can’t really confirm this. Furthermore, it really doesn’t makes a big differences towards normal programmers but may affect those who are working towards micro optimization.  Nonetheless, many people do suggest pre over post increment in term of optimization.

19.    Absolute Path VS Relative Path
Absolute path which is also known as full path compare to a relative path which will be better for PHP? Surprisingly, it seems that absolute path is better. Compare to relative path which might just help to screw up your include and require operation in PHP, absolute path doesn’t. Well, that’s the reason why i use absolute path. But the real reason is that using absolute path eliminate the need for the server to resolve the path for you. Simply to say, do you know where the file is located when you just look at a relative path or is it faster if i just throw you the full path?

20.    Dot Vs Commas Concatenation
Between dot and commas which way do you use to concatenate between two strings/variables? I personally used dot to concatenate my stuff. Such as the one shown below:

$a = '10 PHP programming ';
$b = 'Improvement Tips';
#10 PHP Programming Improvement Tips
echo $a.$b;

I usually do the above. Instead of this,

$a = '10 PHP programming ';
$b = 'Improvement Tips';
#10 PHP Programming Improvement Tips
echo $a , $b;

21.    use gzip compression
Use ob_start() at the beginning of your code. This gives you a 5-15% boost in speed for free on Apache. You can also use gzip compression with ob_gzhandler() for extra fast downloads (this requires spare CPU cycles).

22.    Use unset in larger scripts
unset() variables that are not used anymore to reduce memory usage. This is mostly useful for resources and large arrays.

23.    Reduce Number of Hits to DB
Try to reduce the number of hits to the database. Make queries aggregate so that you call the database less number of times. For example:

$con=mysqli_connect("localhost","username","somepassword","anydb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL" ;
mysqli_connect_error();
}
function insertValue( $val ){
mysqli_query($con,"INSERT INTO tableX (someInteger) VALUES ( $val )");
}
for( $i =0; $i<99; $i++){
//  Calling function to execute query one by one
insertValue( $i );
}
// Closing the connection as best practice
mysqli_close($con);

The script above is much slower than the script below:

$con=mysqli_connect("localhost","username","somepassword","anydb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL" ;
mysqli_connect_error();
}
function insertValues( $val )
{
// Creating query for inserting complete array in single execution.
$query= " INSERT INTO tableX(someInteger) VALUES .implode(',', $val)";
mysqli_query($con, $query);
}
$data = array();
for( $i =0; $i<99; $i++)
{
// Creating an array of data to be inserted.
$data[ ]  =   '(" ' . $i. '")' ;
}
// Inserting the data in a single call
insertValues( $data );
// Closing the connection as a best practice
mysqli_close($con);

24.    Tune your Database
Tune your database and index the fields that are commonly used in your SQL WHERE criteria. ADOdb, the very popular database abstraction library, provides a SQL tuning mode, where you can view your invalid, expensive and suspicious SQL, their execution plans and in which PHP script the SQL was executed.

25.    For MySQL use relevant Storage Engine
Distribute your tasks into reading or writing. Use relevant Storage Engine for reading and writing. Slow writing can go to background process. Use temporary tables to boost writing.

PHP Class & Function Comments

If you have seen that some PHP functions and classes are commented at the top, using a format like this:

/**
 *
 * Convert an object to an array
 *
 * @param    object  $object The object to convert
 * @return   array
 *
 */

So you might be interested what is this format of commenting and where can you find some information on it? so here I tell about commenting PHP functions and class in short!

Functions:

/**
 * Does something interesting
 *
 * @param  Place    $where  Where something interesting takes place
 * @param  integer  $repeat How many times something interesting should happen
 * @throws Some_Exception_Class If something interesting cannot happen
 * @return Status
 */

Classes:

/**
 * Short description for class
 *
 * Long description for class (if any)...
 *
 * @copyright  2006 Zend Technologies
 * @license    http://www.zend.com/license/3_0.txt   PHP License 3.0
 * @version    Release: @package_version@
 * @link       http://dev.zend.com/package/PackageName
 * @since      Class available since Release 1.2.0
 */

That’s basically phpDoc syntax.

You can read more here: phpDocumentor

Securing PHP Apps

The Beginning!

I am going to discuss security issues with PHP web applications that we normally code or what ever you use platform use to develop web applications. When it comes to security, you need to ensure that you write your application to be secure. When you write PHP applications, make sure you look at these guide lines.

  1. Web Forms
  • Secure Web Forms

Normally we see this types of forms, <form action=”/process.php” method=”POST”> but if this is done by <form action=”http://example.org/process.php&#8221; method=”POST”>. This new form can now be located anywhere (a web server is not even necessary, since it only needs to be readable by a web browser), and the form can be manipulated as desired. The absolute URL used in the action attribute causes the POST request to be sent to your sever.
So you need to check what are the requirements of these forms with absolute URLs, in recent development we are talking about nice URLs which may require absolute URLs to be used in images, anchors and locations as well. So try avoiding these absolute URLs in forms.

  • Validate Input

Validating data is the most important habit you can possibly adopt when it comes to security. And when it comes to input, it’s simple: Don’t trust users. Your users are probably good people, and most are likely to use your application exactly as you intended. However, whenever there is chance for input, there is also chance for really, really bad input. As an application developer, you must guard your application against bad input.

For example, say we are creating an application that lists users birthdays and allows users to add their own. We will be wanting to accept a month as a digit between 1-12, a day between 1-31 and a year in the format of YYYY.

Use simple validation techniques with PHP. Here I mentioned a user name validation you can write your own! return 1 is your success case;

case ‘USER_NAME’:
$value = trim($value);
$valueLen = strlen($value);

if($valueLen<3 || $valueLen>256)
return 2;

$pattern = ‘/^([A-Za-z]+[.]{0,1})*[a-z]+$/’;
if (!preg_match($pattern,$value))
return 3;

$values = explode(‘.’ , $value);
$tValues = count($values);
for($i=0 ; $i<$tValues ; $i++)
{
if($this->isRejectedWord($values[$i]) === true)
return 4;
}

return 1;
break;

  • Working with Register Globals

In short, register_globals was meant to help rapid application development. Take for example this URL,
http://yoursite.tld/index.php?var=1, which includes a query string. The register_globals statement allows us to access the value with $var instead of $_GET[‘var’] automatically. This might sound useful to you,
but unfortunately all variables in the code now have this property, and we can now easily get into PHP applications that do not protect against this unintended consequence. The following code snippet is just one
common example you will see in PHP scripts:

if( !empty( $_POST[‘username’] ) && $_POST[‘username’] == ‘test’ && !empty( $_POST[‘password’] ) && $_POST[‘password’] == “test123” )
{
$access = true;
}

If the application is running with register_globals ON, a user could just place access=1 into a query string, and would then have access to whatever the script is running.

  1.  Form Submissions

In order to appreciate the necessity of data filtering, consider the following form located (hypothetically speaking) at http://example.org/form.html:
<form action=”/process.php” method=”POST”>
<select name=”color”>
<option value=”red”>red</option>
<option value=”green”>green</option>
<option value=”blue”>blue</option>
</select>
<input type=”submit” />
</form>
Imagine a potential attacker who saves this HTML and modifies it as follows:
<form action=”http://example.org/process.php&#8221; method=”POST”>
<input type=”text” name=”color” value=”joker” />
<input type=”submit” />
</form>

In PHP script you will be getting this like this $_POST[‘color’] which is absolutely wrong, as mentioned earlier define you domain for your color i.e. red, green and blue are only acceptable.

This form is also accessible form there domain as well, i.e a simple post to http://example.org/process.php from http://localhost/hackphpapp/, then what you need to do here???

With simple tokenism form technique you can create a session based token that is used to valid every form that the form posted from your site only!! here is a PHP example of same our case (improver version of our form post).

session_start();
if (isset($_POST[‘color’]))
{
if (isset($_SESSION[‘token’]) && $_POST[‘token’] == $_SESSION[‘token’])
{
$color= htmlentities($_POST[‘color’]); // remove script injections
if($color == ‘red’ || $color == ‘blue’ || $color == ‘green’)
echo ‘Great! No hack :)’;
}
}

$token = md5(uniqid(rand(), true));
$_SESSION[‘token’] = $token;
?>
<form action=”./process.php” method=”POST”>
<input type=”hidden” name=”token” value=”<?php echo $token; ?>” />
<select name=”color”>
<option value=”red”>red</option>
<option value=”green”>green</option>
<option value=”blue”>blue</option>
</select>
<input type=”submit” />
</form>

  1. Guard your file system
  2. Downloading a file
  3. Secure your database with sql injections
  4. Secure your sessions
  5. Security against Cross-Site Scripting
  6. Security against Cross-Site Request Forgeries (CSRF)
  7. Working with Escape Strings and Magic Quotes

 

session_start();

if (isset($_POST[‘message’]))

{

if (isset($_SESSION[‘token’]) && $_POST[‘token’] == $_SESSION[‘token’])

    {

        $message = htmlentities($_POST[‘message’]);

 

        $fp = fopen(‘./messages.txt’, ‘a’);

        fwrite($fp, “$message<br />”);

        fclose($fp);

    }

}

 

$token = md5(uniqid(rand(), true));

$_SESSION[‘token’] = $token;

 

?>

 

<form method=”POST”>

<input type=”hidden” name=”token” value=”<?php echo $token; ?>” />

<input type=”text” name=”message”><br />

<input type=”submit”>

</form>

PHP IDEs compared!

I’ve talked with many PHP programmers, and one thing that surprises me most is how few use IDEs. Most use text editors, such as Notepad++, dreamweaver.

The text editors I mentioned (and others I didn’t) are great — I don’t want to start a pointless war over which editor is better. However, I have ranked them.

1. Codelobster PHP Edition

Codelobster PHP Edition streamlines and simplifies php development process. You don’t need to keep in mind names of functions, arguments, tags and their attributes; methods etc – we’ve implemented it for you in the autocomplete feature for PHP, HTML, JavaScript and even CSS. Also, you can always get necessary help information by F1 or using special Help control.

Internal free PHP Debugger allows validating code locally. It automatically detects your current server settings and configures corresponding files in order you can use the Debugger.

Supported CMS: Drupal CMS  Joomla CMS  WordPress Blogging Platform

Supported Frameworks: Symfony framework  CakePHP framework  CodeIgniter framework  FaceBook Social Network  Yii framework Smarty Template Engine

Supported JavaScript Libraries: JQuery library

2. PHP Storm

PhpStorm is a lightweight and smart PHP IDE focused on developer productivity that deeply understands your code, provides smart code completion, quick navigation and on-the-fly error checking. It is always ready to help you shape your code, run unit-tests or provide visual debugging.

PHP code completion
PHP refactoring
Smarty and PHPDoc support
Quick navigation
Language mixing (JS/SQL/XML etc.)

3. Net Beans

The NetBeans project offers a version of the IDE tailor-made for developing PHP web sites that comprise a variety of scripting and mark-up languages. The PHP editor is dynamically integrated with HTML, JavaScript and CSS editing features.

Focus on the code and speed up code scanning by excluding individual directories in the Project properties. The NetBeans IDE fully supports iterative development, so testing PHP projects follows the classic patterns familiar to web developers.

The Main features:

PHP Files Without Projects
Rename Refactoring and Instant Rename
PhpDocumentor Support
Zend and Symfony Framework
PHP Source Code Editor
Namespace and Variable Types
Easy Code Navigation
Code Coverage
PHP Unit Testing
Remote and Local Project Development
PHP Debugging
MySQL Integration

4. Eclips

Two plug-ins support PHP in the Eclipse development platform. The first, PHP IDE Project, is an Eclipse Foundation project, which means it is released under the Eclipse license and is developed using the Eclipse Foundation’s tools and processes.

The other is PHPEclipse and is developed independently. As with Eclipse, both run on the Big Three operating systems: Windows, Linux®, and Mac OS X. You can download just the plug-ins (if you already use Eclipse), or download a pre-fab version with everything you need.

Both plug-ins support core IDE features you would expect to find. The code intelligence is rock-solid, pops up when you want it, and displays all the information you need for classes, methods, and arguments.

Figure 1 shows PHPEclipse running on Mac OS X. On the left side is the project view with the files in the project. Below that is the class view, which shows any classes I’ve defined. In the center is my code. I can have multiple files open in multiple tabs simultaneously. On the right side are panels for debugging and browsing. This is the stock PHPEclipse user interface.

5. Komodo

Next up is ActiveState’s Komodo IDE. This IDE runs on Windows, Mac OS X, and Linux, and it supports the usual open source language suspects — Perl, PHP, and Ruby. The code intelligence engine is solid. It scans all your language installations to find custom extensions, such as PEAR modules. On the project side, it supports integration with CVS, Subversion, and Perforce, as well as allowing for direct FTP transfer of code to the server.

Figure 3 shows Komodo running on Windows. A class view is on the left, and the project view is on the right. Dominating the center is the tabbed code view. To the bottom are the breakpoints for the debugger, the command output, and so on. As with all these systems, you can significantly customize the UI to match your preferences.

6. PHP Designer

PHP Designer takes a different tack from the other IDEs. Sure, it supports limited code intelligence. However, its focus is on further enabling the design aspect of the PHP Web application. This is evidenced by its integrated browser being adorned with pixel rulers to help in positioning elements on the page.

  • PHP code completion
  • PHP refactoring
  • Smarty and PHPDoc support
  • Quick navigation
  • Language mixing (JS/SQL/XML etc.)