Common Mistakes to Avoid When Coding in PHP

Despite the high expectations placed on them at times, developers are human. They were the last time we checked anyways.

As humans, we are bound to make mistakes from time to time. And simple, common mistakes often slip past our filters the more comfortable we become with something.

Think about it, when you first started writing code you most likely checked every line to make sure things were perfect. As you grow more comfortable with the process, little things often get overlooked and mistakes are made.

But knowing what these common mistakes are and how to avoid them can really help speed up the development process and keep our clients smiling.

Below you will see some of the more common mistakes that are made with PHP, even by advanced developers…

Poor Housekeeping

People can get lazy and code can get messy.

To keep it organized you can use things like comments and indents. I know, these are basic best practices but think to yourself, when was the last time you hacked up your code without commenting?

I thought so.

How about breaking your code into modules based on function? Many agree that as a rule of thumb your function should not exceed one page on your screen unless it is necessary.

Another good housekeeping practice is to backup all of your files before you upload changes. Sure you may be in a hurry, but the time it takes to make a quick backup is far less than having to go back and undo a disaster.

Forgetting Your Punctuation

One of the best things about PHP is that you don’t need expensive software to write code in. Any text editor will do.

Unfortunately, a basic text editor won’t tell you if something isn’t right.

One of the most common, and basic, mistakes made when coding in PHP is to either forget or misplace a quote, brace or semi-colon causing a syntax error. Before you try to run anything, make sure that every:

  • [ has a ]
  • ( has a )
  • { has a }

Now check to make sure that all string keys are enclosed with matching quotes. Remember, “ does not match with ‘.

While you are at it, double check the semi-colons to make sure they aren’t missing or misplaced.

Forgetting to Validate Input

By now you should know that user provided data cannot be trusted. Allowing this from your users is one way that cross-site scripting, buffer overflows and injection flaws can all be used to attack your site. Unfortunately, it is also one of the most common mistakes people make when coding in PHP.

In the following lines of code, notice that the three variables are not validated:

$birthdate = $_GET['birthdate']; <br>

$birthmonth = $_GET['birthmonth']; <br>

$birthyear = $_GET['birthyear']; <br>

By adding the following lines of code we use preg_match to perform a regular expression match against the input. In our birthdate and birthmonth variables it is checking to verify that a one or two digit number between zero and nine was entered. For birthyear, it needs to be a four digit number between zero and nine:

if (!preg_match("/^[0-9]{1,2}$/", $birthdate)) die("That is not a valid date, please check that again."); <br>
if (!preg_match("/^[0-9]{1,2}$/", $birthmonth)) die("That is not a valid month, please check that again."); <br>
if (!preg_match("/^[0-9]{4}$/", $birthyear)) die("That is not a valid year, please check that again."); <br>

We are able to make sure that the proper type of characters are input by the users are actually numerals and only numerals that we expect to be entered. Anything else results in an error being thrown back to the user.

So I call on our readers to share with us some of the most simple mistakes we have made over the years. And don’t worry, we’re all human here.

SHARE THIS POST
  • http://xangelo.ca Angelo

    Make sure your variable names make sense. Too often I run across code that reads something like ‘$a = 4;’ What is the purpose of $a?

    I know I’m guilty of this too. Normally when doing proof of concept pieces I scatter things like this in to save time or to hack my way around something. Of course, this snippet will almost always end up in production and means nothing to anyone in a few weeks.

    • Anonymous

      Great addition Angelo. I think that all of us can remember a time when we looked back at a variable name and couldn’t remember why we named it as such or what it is supposed to reference.

  • http://twitter.com/pedrotgimenez Pedro Teruel Giménez

    Basic.

  • Anonymous

    This doesn’t have as much as I would have expected for ‘common mistakes’. There are a lot of common mistakes that people make, and some might not realize it (at least we’ve all been there at some point, I imagine), while others might not care. Either way, sloppy code smells worse than I do after a long day in the desert.

    First, I look at code from a documentation standpoint. Does this file or library have a consistent document format? If not, it makes me wonder, “Does this PHP coder use a competent IDE?” I have Zend Eclipse and NuSphere, of which I use NuSphere the most. Typing ‘/**’ and pressing enter auto-fills the PHPDoc structure for me, so a common lack of documentation could be rooted in the lack of an editor, not knowing how to use one, or not realizing documentation can be automatically generated. I currently use DoxBlox, although, I once used PHPDocumentor. Either way, having documentation can be critical for successful code that is expected to be used or worked on in any kind of distributed manner.

    Next, I look at code from a testing standpoint. Does this class or statement have or seem like it should have a test behind it? This is especially true for larger projects. I use PHPUnit to follow Test Driven Development ideologies. This is really useful for build automation, too.

    Then, I look at code for echo/print statements for debugging. To me, at least having the ability to run PHP code through a debugger from code matching the production code environment is a necessity. Seeing execution state and having the ability to use a read-evaluate-print-loop (i.e. Immediate Window) within an IDE with debugging is quite a time saver. You can often test statements, without having to re-start execution. It amazes me how many shops still debug PHP, with echo statements. I’m not saying they’re useless, I just think a debugger can make development and root-cause analysis much faster.

    Another critical mistake, in addition to a failure to keep a backup, is the mistake of not using a SCM. Personally, I would recommend Git, SVN, or CVS, in that order. I use ‘git’ with a master/release/development/feature_name branching strategy that is enforced with granular repository permissions, using ‘gitolite’.

    Speaking of the last four, and adding a whole myriad of possibility to those that would embark on such a journey–I would also say it is a common mistake not to use an automated build system with something like Jenkins or Hudson. I use Jenkins with the PHP for Jenkins template (mess detection, unit tests, etc), that uses an IRC notification bot (easy to use plugin for Jenkins).

    There are many more common mistakes, and I wish I had time to think of more. Anyone want to chip in? This article needs help. :P

  • Sdf

    How about the classic “if ($x = ‘foo’) {}”.

    A nice solution is to invert it and get used to doing if (‘foo’ == $x), as if you miss an ‘=’ that way it’ll show up as a syntax error (easy to spot) rather than a logic error (almost impossible to spot).

    The thing about braces and quotes though, any half decent editor or IDE will spot that for you. Surely nobody is coding in Notepad?

  • Krunal Vaghela

    Thanks for the info’s! Your article actually helped me.

  • http://dhorrigan.com Dan Horrigan

    Common mistake when coding in PHP: Having die() in production code. Don’t teach things that are just stupid to do. Newbies read articles like this and think these are the “correct” way to do things, because you don’t care enough to take a few extra minutes and do proper error handling.

    Common Mistake: Reading developer blogs and taking them at face value and not doing your homework.

    • Anonymous

      You see die() and exit() quite frequently but frequency doesn’t mean it is the best way to do things.

      What do you find to be the best method for validating input?

  • andrew woods

    The preg_match function is part of a suite of functions that’s use Perl compatible regular expressions. That’s where the ‘p’ in preg_ comes from. The older way was to use ereg(), which is on its way out of PHP.

    The ctype functions http://www.php.net/manual/en/ref.ctype.php can also be very helpful when validating input.

    Ok, common mistakes.
    1. Not removing code block comments.
    sometimes developers wrap a block of code in a comment to save it for later. sometimes later never comes and that old code is now just taking space. when you remove these, your code will be much more readable.

    2. mixing display code with application logic

    3. Not respecting the current code standard.
    Everybody has their preferred way to code software. But not following the current style makes it inconsistent. when software is written correctly, it will look like 1 person wrote it, no matter how many people were involved.

    • Anonymous

      Great additions Andrew. Especially removing block comments. I think that is something many of us are guilty of on a regular basis.

  • http://www.webmaisterpro.com/ Kaloyan Banev

    I must admit that I am doing this mistakes nearly everyday, since I switched normal text editor with IDE, mistakes are getting less and easy to find.

  • http://www.webmentor.cr/ Marco Berrocal

    Hello Jeff,

    Just starting with PHP. Love it so far. I have a problem though. I am not so agile with OOP and don’t know if I should go with OOP to program in PHP or I can stick to old-fashion and do modular instead. What do you think I should do? Also, do you recommend any good books on OOP? I started with a Sitepoint one, but damn, think it’s a bit hard.

    • Anonymous

      I am partial to OOP because that is what I am used to. There is a great discussion on the topic here: http://www.worldofwebcraft.com/topic.php?id=1811&t=object_oriented_php_vs_procedural_php that may offer you some more insight.

      As far as books are concerned I would check out the Packt Publishing books. You can register for thier online library and access any of their books whenever you need (Disclaimer – I did write a book for Packt on MediaWiki).

      • http://www.webmentor.cr/ Marco Berrocal

        Just saw that post. See that WAS a question on the back of my mind. Should I go with procedural or OOP in “X” situation. For example, checking if a user’s account is enabled/disabled while he is using the application, I would go with the object to check as I have to use it in every instance while the user is logged in, right?

        About the books, don’t worry about it. I think it’s always good to see other people’s point before coming to your own conclusions. If the book does the job, great if not, keep going til the answers come :)

  • http://www.konoozi.com/web-design-california/ Web Design California

    I found this post really interesting, I work for a Web Design company, when working with clients I am always extra careful to keep constant contact, checking that they are up-to-date and happy with the progress. I find that although there will always be difficult clients keeping in touch gives you the opportunity the deal with issues as they arise, and always get confirmations in writing!