Php tips and tricks

GFX9.COM share Php tips and tricks, you can download now.

Tags: , .

Let’s target the elephant in the room: PHP has been on the receiving end of a considerable amount of flack in the last few years. Well, who are we kidding? It’s always served as the punching bag for the “cool kids”! But there’s just one thing; despite all of this ridicule, PHP continues, with ease, to remain infinitely more popular than its server-side competitors - in terms of users.

So how can a language as mocked as PHP be so popular? The answer is simple: PHP was specifically built for the web. Once installed, a beginner can execute his first PHP command, and view the output in a web browser in less than a minute. Do not underestimate how significant this is.

Are the Criticisms Warranted?

It’s important that we never blindly choose sides; we must always remain objective.

Is PHP the most beautiful of languages? Certainly not; spend a few days with Ruby or
Python, and you’ll be introduced to significantly more elegant languages.

Is PHP littered with inconsistencies, ranging from out-of-sequence parameters, to confusing capitalization? Heck yes it is!

But, is PHP the easiest server-side language to get started with? Without a doubt, yes. This leads many to assume that PHP developers are ignorant and inexperienced. This couldn’t be further from the truth. Sure, with popularity comes a wave of newcomers; but that’s a good thing! They’re the next generation. This level of popularity also comes with countless seasoned developers. Is it possible to write beautiful code in PHP? Gosh, yes. One only needs to review modern frameworks, such as Laravel, to confirm this truth.

Laravel is a new, expressive PHP framework, which is rapidly gaining popularity in the community.

So yes, PHP has its share of problems; but all languages do. Trust me when I tell you that “WAT” is sprinkled throughout every language. The difference is that seasoned developers know how to leverage the good parts of the language.

Now that we’ve established that PHP is certainly not a language to be embarrased by, I’d like to share twenty various tips with you - everything from fun simple tricks, to best practices, to some of the new syntax options in PHP 5.4.

PHP 5.4

The latest and greatest version of PHP, version 5.4, was released on March 1st, 2012. With this release came a variety of new improvements - some of which I’ll illustrate in this article.

It’s very possible, however, that you’re using a MAMP or WAMP stack. If so, you may find that version 5.4 isn’t available to use yet. At the time of this publication, this is true for the massively popular MAMP app, avaiable at

While is easily the most popular stack for Mac, it’s also one of the most rarely updated.

To get around this, we have two options:

  • Compile the latest version of PHP, which frequently isn’t as simple as we might hope.
  • Make use of a different MAMP/WAMP stack, including Bitnami, Zend Server, XAMPP, and AMPPS

Please note that, if you intend to take advantage of PHP 5.4’s new features, then you should also ensure that your web host has upgraded as well.

Array Bracket Notation

We’re all familiar with the basic syntax for creating simple arrays:

// Simple Array 
$myArray = array('one', 'two', 'three'); 
// Associative 
$myArray = array( 
    'first' => 'Napoleon', 
    'last'  => 'Dynamite' 

In PHP 5.4, we can use a streamlined, bracket notation that JavaScript developers will immediately recognize!

// Simple Array 
$myArray = ['one', 'two', 'three']; 
// Associative 
$myArray = [ 
    'first' => 'Napoleon', 
    'last'  => 'Dynamite' 

Particularly as a developer whose time is split equally between JavaScript and PHP, this is a welcomed addition to the language. The less language shuffling we have to perform in our heads, the better.

Short Tags

Those of us who have been working in PHP for quite some time will be familiar with a few different methods for embedding PHP into a page: short tags, ASP tags, and the standard method that most use today.

// Standard 
// ASP Style 
<% echo 'hello'; %> 
// Short Tags 

Please don’t use the ASP method. It’s disabled in your php.ini file by default, and for good reason. As of PHP 5.3, short tags were largely discouraged, and labeled as a bad practice. The reason for this was because there was no guarantee that the server would have short tags enabled. As a result, most of us generally recommended that all PHP developers stick with the standard form: .

As of version 5.4, however, this is no longer the case for the echo short tag syntax: . You are free to use this shorthand syntax without worry, due to the fact that, now, has been decoupled from the short_tag setting, regardless of what is declared in the configuration file.

Get off mysql_connect

One of the most frequent criticisms of PHP is that it’s open to a variety of attacks. Unfortunately, these critics are misinformed. The truth is that, yes, if the developer is not being responsible, a PHP application can be the victim to all sorts of attacks, ranging from SQL injection, to CSRF. That said, as long as he follows a few simple guidelines, this quickly becomes, as much as possible, a non-issue.

Easily, the most ubiquitous of PHP mistakes stems from SQL injection. The basic concept is that the developer unwisely allows user input to be embedded into a SQL query. Consider the following scenario:

'SELECT * from myTable WHERE id="' . $_GET['id'] . '"';

This is terrible! You assume that the id key from the $_GET super-global array will indeed be an integer, at which point you can select the desired row from the table. But what if I instead cleverly end the query, and drop the table?

$_GET['id'] = '"; drop table myTable';

Yep, that value will then be directly embedded into the SQL query, like so:

'SELECT * from myTable WHERE id = ""; drop table myTable';

Goodbye table! Another example would be to translate a request for a single row in the database into one for all the rows.

$_GET['id'] = '"" or 1'; 
'SELECT * from myTable WHERE id = '"" or 1';

By passing or 1, we’ve now specified that, because 1 will always be true, the SQL query should return all rows from the table!

A basic rule of thumb is to treat all user-supplied data as malicious. There are a multitude of ways to protect against these types of attacks, including the use of mysql_real_escape_string.

Though this will work, save yourself the worry and stop using the basic mysql API to query your database. PHP actually provides three different APIs for connecting to a MySQL database - mysql being the last one you should use.

Note: mysql_connect is expected to become deprecated in a future release of PHP.

Instead, take advantage of the PDO API and prepared statements. The advantage to this technique is that the user-supplied data is never physically attached to the SQL query. This way, it’s not possible (well, nothing is impossible) for the user to embed malicious data that will harm your data structure.

With PDO and prepared statements, we can do:

$conn = new PDO("mysql:host=localhost;dbname=myDatabase", $username, $password); 
 // Use real prepared statements. Don't emulate. 
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
$stmt = $conn->prepare('SELECT * from myTable WHERE id = :id'); 
    ':id' => $_GET['id'] 
$results = $stmt->fetchAll(PDO::FETCH_OBJ);

The considerable advantage to this method is that the parameters are being bound after your SQL query has been prepared.

Note: if you come across articles on the web that make reference to the performance differences between using the traditional mysql API, versus PDO, ignore them. The variance is negligible.

Regular Expressions With the X Flag

While some of us (shamefully raises hand) truly enjoy regular expressions, they certainly aren’t for everyone. Many times, you’ll find that the intricate sequence that you wrote months ago, now, might as well be gibberish.

The x flag can help in these situations. Think of it as a way to embed comments into a regular expression, for future reference.

Consider the following simple regex, which verifies a US phone number:


While we may currently understand each section of the regular expression, in a year’s time, we may have no clue what the ?: does at the beginning (it designates a non-matching group, by the way).

Let’s instead use the x flag to inform our future selves.

    (?:d{3})?  # The area code… code can be optional 
    -?d{3}         # The prefix 
    -?d{4}         # The line number 

This is admittedly a simple example, but, certainly, you can imagine the benefits that it can provide for more intricate regular expressions.

A Built-In Web Server

As of PHP 5.4, we can finally make use of its built in web server. Simply browse to the directory on your computer where your PHP application is stored (regardless of whether it’s in Apache’s document root) in the command line, and type:

php -S localhost:8888

This will create a development server for the current folder on port 8888.

PHP 5.4.3 Development Server started at Saturday May 26 13:07:59 2012

Browse to localhost:8888 in your web browser, and voila: instant server for the current directory in seconds!

CSS Variables with PHP

These days, most designers take advantage of a CSS preprocessor, such as Less or Sass. However, there are some cases when a smaller project doesn’t necessarily warrant a preprocessor, though you still might like to leverage the power of variables.

Well, if we’re clever, we can do this very thing with plain-old PHP! First, let’s review the basic concept. Consider the following file, style.php, which contains a list of PHP variables and CSS:

.container { 
  margin: 0; 
  padding: 20px; 
  color: ; 

Believe it or not, if you reference this file in your HTML:

It will work! However, there are some considerable downsides to this approach, if used in production. Most notably, because we’re using PHP, the file never has the chance to be cached (at least not without a bit of trickery). Instead, a better solution is to use this technique for development, and then convert the file to CSS for production. This conversion can be done from the command line.

php style.php > style.css

The command above will execute the PHP, and export the output to a file, called style.css. With this technique, you’re able to leverage the power of variables (and PHP), while still ultimately outputting a static stylesheet for production.

Random Header Images

Don’t underestimate how convenient the technique outlined in this previous tip can be. We’re not merely limited to variables; if you instead choose to render the style.php file in production, you can accomplish a variety of dynamic tasks, such as loading random header images on each page load.

For example:

.header { 
    background: url(images/.jpg) no-repeat; 

With this technique, each time the page is rendered, the stylesheet will reference a random image within the images/ folder. Populate that folder with ten images - 1.jpg to 10.jpg - and you’re all set to go!

If you do elect to serve PHP files as CSS, please do your research first.

Don’t Split Hairs

It only takes a Google search to uncover countless articles related to PHP performance. What’s unfortunate is that the huge majority of these articles are misinformed, or focus on “performance boosts,” which are insignificant to an extreme.

Consider the popular “single vs. double quotes” debate. For those unfamiliar, the basic argument is that, because PHP doesn’t have to parse single quotes, in search of embedded variables, it’s better for performance to, when possible, always use singles.

$name = 'Bob'; 
echo 'Hi, $name'; // Hi, $name 
echo "Hi, $name"; // Hi, Bob

Not only is this not true, but it takes the concept of pre-optimization to an extreme. Any article that states otherwise is providing a poor service, and is harming the PHP community (particularly the newcomers) more than helping it.

Instead, invest your performance tuning into database query bottlenecks, and on the front-end - concatenating assets, and reducing the size of your images.

Don’t Show Off

There tends to be a natural progression for new developers: Learn, Discover, Abuse, Mature.

  • Learn the basics
  • Discover the tricks and shorthand
  • Abuse the shorthand, creating unreadable code
  • Mature as a developer, and embrace readability

Your goal is to reach that fourth stage: maturity. While it’s fun to test ourselves to see just how much logic we can fit into a single line, doing so is largely considered bad practice. Remember: readability trumps everything. If three extra lines will make the code significantly more readable in six months, then certainly add those three lines!

Embrace Modern Frameworks

As designers, sometimes it’s easy to fall into the rut of always resorting to WordPress, when a new project arises. Certainly, WordPress can be incredibly convenient, but it’s just a tool - and every project has a right tool for the job.

If you happen to fall into this category, consider - assuming the project requires one - using a modern PHP framework, such as FuelPHP or Laravel - the latter of which is quickly sky-rocketing in popularity this year.

Laravel is an extremely expressive framework that makes coding in PHP fun again! For instance, consider the monotonous task of creating a users table. In Laravel, rather than building up some SQL string, we can instead harness the power and flexibility of migrations.

Using Laravel’s helpful command line tool, artisan, we can create the necessary skeleton for both creating and dropping the users table.

php artisan migrate:make create_users;

This code will generate a Create_Users migration, along with two methods: up and down. At this point, we can leverage the helpful Schema class to build our table, without having to nest nasty SQL into our PHP.

Here’s an example:

class Create_Users { 
    /* Create the table. */ 
    public function up() 
        Schema::create('users', function($table) { 
    /* Revert the changes to the database. */ 
    public function down() 

Notice how expressive this code is? I challenge you to read it, and not immediately recognize what’s taking place. The table can now be created by executing:

php artisan migrate

And that’s it; your table has been created!

The power of migrations is in the fact that, if needed, we can easily roll back these changes with a simple command:

php artisan migrate:rollback

Now, the table has been dropped, or deleted.

This is only a single example of the power that a modern framework like Laravel can provide. Don’t be afraid to dive in; frameworks aren’t as scary as they may appear!

Blade Templating

Need another reason to consider Laravel? Enter Blade templating. Most frameworks offer some form of templating solution, but Blade ranks among the best. We all hate the process of creating forms; well Blade makes the task considerably less groan-worthy!

Blade allows you to use beautiful, unobtrusive syntax for writing PHP control structures and echoing data.

Rather than embedding , we instead can use a curly brace notation: {{ }}. Here’s an example:

{{ Form::open('task/5', 'PUT') }} 
  • {{ Form::label('title', 'Title') }} {{ Form::text('title') }}
  • {{ Form::label('message', 'Message') }} {{ Form::text('message') }}
  • {{ Form::submit('Update Task!') }}
{{ Form::close() }}

Much easier on the eyes, ay?

Jump to the Cloud

It’s quite possible - likely even - that your standard deployment process consists of opening an FTP program, such as Transmit, and dragging the updated folder over to your server. Clearly, this isn’t ideal; what if you make a mistake, and need to roll back to the point before you uploaded those files? There isn’t an easy way to accomplish this with the “drag and drop” method.

Instead, a better solution is to store your app in the cloud, and use Git-based deployment. Consider using a platform such as PHPFog or Pagoda Box, which provide fast and scalable hosting for your PHP projects and applications.

PHPFog is a popular cloud platform for PHP applications.

With this method, deploying your project can 100% be accomplished from the command line.

git add . # add all changed files to the stage 
git commit -m 'Added about page' # commit the changes 
git push origin master # push the changes to PHPFog

With these three simple commands (which can be shortened further with aliases), we’ve now leveraged the power of version control with Git, and have pushed the latest modifications to PHPFog.

Next, referring back to the “roll back” question that I proposed earlier, should we need to “undo” those updates, it’s as simple as running:

git reset HEAD^ --hard 
git push origin -f

This snippet will reset your code base to the state that it was in before the commit, and then force a push to PHPFog.

In a modern development world, version control and Git deploment is the standard. Are you using it?


JavaScript users have enjoyed the power of closures for years now. Luckily, we now have them in PHP, as of version 5.3! If the term, “closure” sounds scary, just think of it as an anonymous function.

Most immediately, you can imagine using them as callback functions, similar to what you might be used to in jQuery. Here’s a WordPress example:

add_action('publish_post', function() { 
    // send email to subscribers 

Additionally, closures can be assigned to variables.

$name = function() { 
    return 'Douglas Quaid'; 
$name(); // Douglas Quaid

Even better, a closure can inherit values from its parent’s scope, via the use keyword.

Please note that, as of version 5.4, within a closure, the $this keyword will still refer to the current class instance.

Joke of the Day

So, you want to display a unique joke on your website with each page load? That’s a cinch. First, we can store a list of joke within an array.

$jokes = [ 
    'Why did the chicken cross the road? To get to the other side.', 
    'What is Ernie's favorite ice cream? Sure-Bert.', 

Next, with each page load, we randomly select an item from the array, and echo it within a blockquote.

Joke Of The Day

It couldn’t be simpler!

Easy Documentation

PHP is an inconsistent language, particularly when it comes to things such as the argument order for its various functions. Do we set the haystack as the first or second parameter of the stristr function? It’s easy to forget.

Assuming that you’re not using an IDE, you likely perform a quick Google search for the solution. An easier method is to pull up the Terminal, and type:


Referring back to the previous example, to determine the correct argument order for the stristr function, we can run:

php --rf stristr

This command will return:

Function [  function stristr ] { 
  - Parameters [3] { 
    Parameter #0 [  $haystack ] 
    Parameter #1 [  $needle ] 
    Parameter #2 [  $part ] 

That was easy! Now we can easily see that, yes, the haystack should be set as the first parameter.

Create Thumbnails

The GD library, though cumbersome to work with, can provide a great deal of power, when it comes to manipulating images. For instance, to create a thumbnail dynamically, we can follow a few steps:

First, we use the imagecreatefromjpeg function to load the image from the file system. Next, we use getimagesize to determine the width and height of the image. This function will return an array, whcih contains a variety of information about the image, including, of course, the dimensions, as well as the file type. In our case, we only need the dimensions, so we’ll use the list function, to store the first two items in the array within the $x and $y variables, respectively.

$source = 'webdesigner.jpg'; 
$original = imagecreatefromjpeg($source); 
list($x, $y) = getimagesize($source);

Next, we specify our desired dimensions for the thumbnail.

$desired_width = 200; 
$desired_height = $y / ( $x / $desired_width );

We’ve set a width of 200, and are using just a bit of math to calculate what the y value should proportionally be.

Now, we’re ready to begin generating the thumbnail, using the imagecreatetruecolor function.

$thumb = imagecreatetruecolor($desired_width, $desired_height);

This will set the wrapper for the thumbnail. Next, we copy the modified original image into this $thumb destination.

// dest, original image, dest_x, dest_x, src_x, src_y, dest_w, dest_h, src_w, src_h 
imagecopyresampled($thumb, $original, 0, 0, 0, 0, $desired_width, $desired_height, $x, $y);

Yes, by the way, this function is a bit ridiculous. Don’t worry; none of us can remember the order for the arguments. Mostly, we’re specifying which portion of the original image to copy (the whole thing, in our case), as well as the dimensions of the destination and source images.

The final step is to set the content type header, and output the image to the browser.

header("Content-type: image/jpeg"); 

Alternatively, if you’d instead prefer to write the thumbnail to a file, rather than render it on the screen, you can pass a file name as the second argument for imagejpeg.

imagejpeg($thumb, 'image-thumb.jpg');

Clearly, this is a simple, procedural implementation. You’ll likely want to abstract this functionality away to a flexible and reusable class.

Use Xdebug

For the times when you need more debugging power for your application, consider using the fantastic PHP extension, Xdebug.

Xdebug provides full stack errors, profiling, and code coverage analysis. While you can download it directly from the Xdebug website, it’s very possible that you already have it setup on your system; you only need to activate it.

To do so, open your php.ini file, search for [xdebug], and uncomment the zend_extension line below it, by deleting the semi-colon at the beginning of the line.

Note: if you don’t know where your php.ini file is stored, open the Terminal, and run php -i | grep "Loaded Configuration File". This should output the path to the file.

Next, you’ll also want to enable HTML errors as well. Search for html_errors, and change the value to On.

Lastly, restart Apache, and you’re good to go!

The default error logging.

Improved debugging with Xdebug.

Finding Files With Glob()

So you need to search a directory for a certain set of files; with the glob function, this is a cinch. Let’s hunt down all JPEGs in the current directory.

$files = glob('*.jpg'); 

The snippet above will output:

    [0] => image.jpg 
    [1] => people.jpg 
    [2] => photo.jpg 

That’s helpful, but what about images with the jpeg and png extensions? To capture those files as well, we can use the GLOB_BRACE flag.

$files = glob('*.{jpg,jpeg,png}', GLOB_BRACE); 

Now, we’re capturing all images - or at least files, which have extensions of png, jpg, and jpeg.

    [0] => image.jpg 
    [1] => people.jpg 
    [2] => photo.jpg 
    [3] => city.jpeg 

For one last glob tip, if you want to return the full path to the captured files, we can do so quite easily:

$files = glob('*.{jpg,jpeg,png}', GLOB_BRACE); 
$files = array_map('realpath', $files); 

Which outputs:

    [0] => /Applications/MAMP/htdocs/project/image.jpg 
    [1] => /Applications/MAMP/htdocs/project/people.jpg 
    [2] => /Applications/MAMP/htdocs/project/photo.jpg 
    [3] => /Applications/MAMP/htdocs/project/city.jpeg 

Trust No One, Mr. Mulder

When it comes to tip-style articles, there’s one golden rule, which I refer to as the X-Files rule: “Trust no one.” This includes me! Consider the techniques that you learn in magazines and blogs as guidelines, which are meant to be questioned and tested. Don’t blindly accept a set of rules as “the rules.” Trust no one, and question everything - especially when rules are meant to be broken!

submit to reddit

Similar content