All in the <head> – Ponderings and code by Drew McLellan –

Experience is More Important than Knowledge Of Syntax

I’m still pretty much learning PHP. Having a lot of experience in ASP, and going back further, perl, stands me in excellent stead. Over the years I’ve taught myself a number of different languages, starting with BASIC when I was roughly seven years of age, so I’m pretty comfortable with reading technical documentation and gleaning the information I need. After all, when designing a web application (as I’ve noted previously) it’s the logic that is key, rather than the code. Code can be looked up.

What you can’t gain from the manual, however, is the lessons learned from experience. The user comments on PHP.net give a snapshot of various peoples’ experiences, but it’s incredibly hard to learn from other peoples’ mistakes when it comes to code. The manual can tell you how to use each aspect of the technology, but it won’t tell you what’s best to use in each precise circumstance. There are some things you just have to learn for yourself.

That’s where I am with PHP. I can happily code away, looking up what I need to look up. I know from other programming experience to design by application to be as object-oriented as I can. I know from business experience which elements need to be flexible to the client’s demands. I know from web experience how best to handle security and user input. What I don’t know is how best to do things in PHP.

A case in point. PHP has a really fantastic feature called Magic Quotes. This option, which is set server-wide in the php.ini configuration file, automatically escapes quotes in any user input (GET, POST and cookies). This essentially protects against basic security threats like SQL Injection Attacks, and so enables novice coders and conscientious server admins to sleep at night. For the rest of us it saves an extra step in protecting our code, as we know this is being taken care of.

But do we? As Magic Quotes is a option, it’s enabled on some servers and not on others. This means that if you play it safe and manually use addslashes() to escape your user input, that same input is going to get doubly escaped on a server with Magic Quotes enabled. If you don’t manually protect yourself, you are open to attack on servers that don’t have Magic Quotes enabled. You’re damned if you do and you’re damned if you don’t. That’s the sort of thing you don’t learn from the documentation.

This particular idiosyncrasy burned my fingers today. Not in any major way, but it lost me time and set me back a bit. From experience I now know to do this:

function autoslash($str){
if (!get_magic_quotes_gpc()) {
return addslashes($str);
}else{
return $str;
}
}

If I apply autoslash() to all user input I can be sure that quotes will be escaped predictably, as the function is checking to see if Magic Quotes are on or off.

Writing the code is the easy bit, but experience is more important than knowledge of syntax.