Simple PHP Best Practices

This post is intended to make you think a little bit more about some of the habits you may have formed whilst programming. It is not the nirvana of programming, nor best practice, just a few little ideas to help you along the way.

1. Use descriptive variable names
Arguably this is the hallmark of the inexperienced or just plain poor programmer. Using variables names such as $x or $y makes a major sacrifice in readability for a negligible performance improvement.
Remember, variable names are cheap whilst programmer time is not.

2. No commented out code
Sure, commenting out code makes sense if you do not use a revision control system (like CVS/SVN/Git/etc) however, – why on earth are you not using a revision control system?
Leaving commented code behind tends to clutter files and reduces readability, – especially in those hard times on a console and don’t have the luxury of an editor with syntax highlighting and large resolution.

3. Write control structures as you would say them
It is all too easy to make control structures (if, switch, while, etc…) unreadable. An easy trick to improve readability is to read it to yourself, from start to finish; this forces you to read it anew and clears up strange comparisons such as: ‘!$security_check===false’.

4. Use single quotes (‘) by default and double quotes only when you want to put variables in your string
It’s the little things…

Is PHP Agile?

A client recently asked if PHP was an Agile programming language, and during the (rather lengthy) explanation a few principles worth exploring were covered:

In the context of software development Agile is really no more than a set of principles and values. At a meeting in February 2001 people who were then developing software differently to traditional processes drew up a manifesto; they formalised practices favouring constant feedback and change, flat hierachy, and delivered early and often.

PHP is generally considered a lightweight language, – often it is used because it can get things done quicker than with other languages. A language is never agile because it does not generally define the processes used when developing with it. However it can have qualities that can make its development quicker; PHP is light, interpreted, and it is simple. Unfortunately these reasons have also attracted people unconcerned with best practices in order to ‘just get their sites up and running’

Agile doesnt mean doing the job quickly, – dont expect to finish the project earlier, but you will deliver earlier. A part of the system that is testable, usable, and something that adds value. From the feedback the team and customer will decide what will be delivered next. The iterations are closer together than other approaches and in order to deliver quickly you will only deliver what you need.

As far as web application development is concerned, being an interpreted, lightweight, embeddable, simple language, with fairly reasonable object oriented support, PHP is in a fairly unique position to fulfill the needs of agile development teams. The elements are available, but of course it is up to the enterprises to take the step and use what is there for setting up their own agile development environment.

Obfuscating email with PHP

This is a function to protect email addresses on your website from bots or spiders that harvest email addresses for spam purposes; it uses a substitution cipher generating a unique key for every page load.
PHP encrypts your email address and generates javascript to decrypt it because most bots and spiders can’t execute javascript. A visitor of your web page will not notice this as long as they have javascript enabled, otherwise they will see “[javascript protected email address]”

As the script contains quite a lot of special characters, a downloadable version is available here

Usage
echo hide_email(‘test@test.com’);

Further reading
Ross Killen’s implementation here
Methods to hide email addresses in page source here

Dont copy variables without reason

php-logo

Sometimes PHP novices attempt to make cleaner or more legible code by copying predefined variables to variables with shortened names prior to working with them. This actually results in doubled memory consumption (when the variable is altered) and therefore slower scripts. In the following example, if a user had inserted 512KB worth of characters into a textarea field this would result in nearly 1MB of memory being used.


$title = strip_tags($_POST['title']);
echo $title;

This operation can be performed inline, – avoiding the memory overhead.


echo strip_tags($_POST['title']);

PHP Twitter Class

php-logo

Twitter is a service for friends, family, and co-workers to communicate and stay connected through the exchange of quick, frequent answers to one simple question: What are you doing?

PHP Twitter is a (wrapper)class to communicate with the Twitter API written by Tijs Verkoyen. Download page is available here

A quote from the author (and he’s not wrong) The class is well documented inline. If you use a decent IDE you’ll see that each method is documented with PHPDoc. There is also a tutorial available here

So, to sum up, these links should kickstart your twittering ability from PHP (and your website).

Happy tweeting!

The future of PHP

php-logo

A few changes in PHP 6:

This post is mainly about what is removed (and will no doubt break countless scripts out there)

  • magic quotes
  • register_globals
  • register_long_arrays
  • safe_mode

magic_quotes


// Assuming magic_quotes is on
$sql = "INSERT INTO USERS (USERNAME) VALUES $_GET['username'];

// Using proper parameterised query method (MySQL)
$statement = $dbh->prepare("INSERT INTO USERS (USERNAME) VALUES ?";
$statement->execute(array($_GET['username']));

Obviously the get_magic_quotes_gpc() function will no longer be available.

register_globals

// a security hole because if register_globals is on the value for user_authorised can be set by a user sending
// them in the query string
// i.e www.example.com/index.php?user_authorised=true
if ($user_authorised){
// show all the data
}

// Being specifc
function is_authorised{
if (isset($_SESSION['user'])){
return true;
}else{
return false;
}
}
$user_authorised = is_authorised();

register_long_arrays

Using deprecated registered arrays:

// Echo the name of the user value given on the query string
// http://www.example.com/index.php?username=notgood
echo "Welcome, $HTTP_GET_VARS['username']";

Using $_GET

// Using the supported $_GET array instead
echo "Welcom, $_GET['username']@;

safe_mode
This was originally to ensure that the owner of a file being operated on matches the owner of the script that is executing. It was originally a way to attempt to handle security when operating on a shared server environment (like many ISPs would have) It is outside the scope of this blog to document the numerous functions affected by this change, so consult your documentation.

Finding true IP address using PHP

php-logo

Sometimes a browser may be hiding behind a proxy, – this little function will hopefully get to the root of things:

function userIP(){
// Returns the True IP of the client calling the requested page by first checking to see if HTTP_X_FORWARDED_FOR has a value (proxy)
$userIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
if($userIP == ""){
$userIP = $_SERVER['REMOTE_ADDR'];
}
// Return the IP we've figured out:
return $userIP;
}