Top Ten Tips for Getting Started with PHP

Here are ten tips that will help you avoid some of the most common pitfalls when coding Web applications in PHP.
3. Headers before Anything Else!

You can generate and transmit any kind of HTTP header before even starting to build the actual Web page. However, you must remember that header() has to be called before any HTML code or PHP output, including blank or empty lines! Code like this, for example:


<?php /* any PHP command(s) here */ ?>

<?php header("Content-type: image/png"); ?>

will not work. The mere presence of the empty line between the two encoded PHP statements will cause PHP to transmit standard HTTP headers, which almost always will not be what you wanted (otherwise you would not have used that function). Note that the blank line may even be...in another file. That is, the same thing will happen if you load PHP code from some external file that doesn't end exactly with the closing ?> PHP tag.

This is a frequent cause of headaches for programmers who build sites that use cookies. The only way to make cookies work is to handle them before your PHP program sends header information. If you don't realize that a simple blank line sends header information, you can stare at your code for hours wondering why you are having problems with cookies. After all, you do handle cookies before you deliberately send the header. What you don't necessarily notice is that there's a blank line in your program (or included file) that is sending headers without your knowledge, which is why your cookies don't work.

4. Always Check User Data (and Beware of E-mail Addresses)

You should always validate data that your pages receive from the Web. JavaScript routines that validate form input on the user browser are useless security-wise. Nothing prevents a cracker from sending malicious data directly to your code. Imagine a PHP shopping cart that can show all the items below the $HIGHEST_PRICE decided by the user. If, without previous checks, you merrily performed a database query with a $HIGHEST_PRICE whose value is something like “delete * from my_database;”, don't complain when your on-line store looks empty!

You can validate data using a combination of three techniques. The first is to analyze the data with regular expressions that explicitly define only the formats that are allowed; a phone number or year of birth, for example, can contain only digits, so pass it through the function is_digit().

The second is to use other functions like EscapeShellCmd(), which can block “data” from executing unwanted system commands, or mysql_escape_string() on variables that must be inserted into an SQL statement.

The last type of validation strictly depends on the actual meaning of a variable and the context in which it is used. Only you can help yourself here. For example, 5555555 is made only of digits, but (in North America) it is not a valid phone number. It should be allowed only if the user declared to be from another country. Similarly, although 18 is a perfectly valid $AGE, a script offering discounts to senior citizens should refuse it, right?

E-mail addresses are particularly troublesome from this point of view. There are several functions that validate their syntactical correctness, like the one at www.zend.com/tips/tips.php?id=224&single=1. They do nothing, however, to guarantee that an address does belong to the person who sent it, or that it exists at all, such as Luke.Skywalker@whitehouse.gov. Well, it's probably a safe assumption that there is no Luke.Skywalker in the White House, anyway. Always ask users to reply to a confirmation message or open a socket to their mail server to check whether they exist.

5. Properly Manage Quotes and Escapes

What will appear in your browser if you load this very simple PHP code?


<? php
$HOME = 'a sweet place';
print "1: $HOME<br>"; // double quotes
print '2: $HOME<br>'; // single quotes
?>

The answer is these two lines of text:


1: a sweet place
2: $HOME

Double quotes make PHP replace any variable inside them with its current value. The content of single quotes is treated like one monolithic, opaque block that can be copied or printed only, not modified. The same applies when you use quotes to build the keys of an associative array. $my_array['$HOME'] and $my_array[“$HOME”] will be different elements. That's it. Still, it is very easy to forget this distinction and use one when you meant the other, or no quote at all. Therefore, when something doesn't have the value you expected, check the quotes first.

Because user data cannot be trusted, PHP can be set up to escape with slashes automatically with all the $_POST sent by an HTML form to the script. Actually, even internal data could contain slashes, to escape special characters, which must be removed before processing them. The solution is to use the stripslashes function, as in this example straight from the on-line PHP manual:


<?php
$str = "Is your name O\'reilly?";
// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>

______________________

Articles about Digital Rights and more at http://stop.zona-m.net CV, talks and bio at http://mfioretti.com

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState