Are You Making These 10 PHP Mistakes?

    One of the best things about PHP is that it’s a great language to just “dive into”, thanks to its wide-ranging popularity. Anyone with the ability to hit “Search” on Google can quickly create a program. However, this also lends to a major criticism of PHP: it’s almost too easy to find and reproduce bad code.

    Here are 10 PHP mistakes that any programmer, regardless of skill level, might make at any given time. Some of the mistakes are very basic, but trip up even the best PHP programmer. Other mistakes are hard to spot (even with strict error reporting). But all of these mistakes have one thing in common: They’re easy to avoid.

    Take the time and make sure that your PHP is secure, clean and running smoothly by checking your site for these common PHP blunders.

    1. Single quotes, double quotes

    It’s easy to just use double quotes when concatenating strings because it parses everything neatly without having to deal with escaping characters and using dot values. However, using single quotes has considerable performance gains, as it requires less processing.

    Consider this string:

    # $howdy = 'everyone'; 
    # $foo = 'hello $howdy'; 
    # $bar = "hello $howdy";
    

    $foo outputs to “hello $howdy” and $bar gives us “hello everyone”. That’s one less step that PHP has to process. It’s a small change that can make significant gains in the performance of the code.


    Photo by dantaylor.

    2. Semicolon after a While

    It’s funny how one little character can create havoc in a program, without even being reported to the PHP error logs! Such as it is with semicolons and While statements.

    Codeutopia has an excellent example of this little error, showing that these nasty errors don’t even get reported (even to E_ALL!), as it quietly falls into a silent loop.

    $i = 0;
    while($i < 20); {
      //some code here
      $i++;
    }
    

    Omit the ; after the while statement, and your code is in the clear.


    Photo by RTPeat.

    3. NOT Using database caching

    If you're using a database in your PHP application, it is strongly advised that you at least use some sort of database caching. Memcached has emerged as the most poplar caching system, with mammoth sites like Facebook endorsing the software.

    Memcached is free and can provide very significant gains to your software. If your PHP is going into production, it's strongly advised to use the caching system.

    4. Missing Semicolon After a Break or a Continue

    Like #2, a misused semicolon can create serious problems while silently slipping off into the shadows, making it quite difficult to track the error down.

    If you're using a semicolon after a "break" or "continue" in your code, it will convince the code to output a "0" and exit. This could cause some serious head scratching. You can avoid this by using braces with PHP control structures (via CodeUtopia).


    Photo by ed_gaillard.

    5. Not Using E_ALL Reporting

    Error reporting is a very handy feature in PHP, and if you're not already using it, you should really turn it on. Error reporting takes much of the guesswork out of debugging code, and speeds up your overall development time.

    While many PHP programmers may use error reporting, many aren't utilizing the full extent of error reporting. E_ALL is a very strict type of error reporting, and using it ensures that even the smallest error is reported. (That's a good thing if you're wanting to write great code.)

    When you're done developing your program, be sure to turn off your reporting, as your users probably won't want to see a bunch of error messages on pages that otherwise appear fine. (Even with the E_ALL error reporting on they hopefully won't see any errors anyway, but mistakes do happen.)


    Photo by Eliya.

    6. Not Setting Time Limits On PHP Scripts

    When PHP scripts run, it's assumed that they'll eventually finish in a timely manner. But every good programmer knows that nothing should be assumed in a piece of code. Nothing makes a program crankier than an unresponsive script.

    You can get around this issue by simply setting a time limit on the script (set_time_limit). While it may seem like a trivial thing, it's always clever to prepare for the worst.

    7. Not Protecting Session ID's

    A very common PHP security mistake is not protecting session ID's with at least some sort of encryption. Not protecting these Session ID's is almost as bad as giving away a user's passwords. A hacker could swoop in and steal a session ID, potentially giving him sensitive information. MT Soft an example of how to protect Session ID's with sha1:

    if ($_SESSION['sha1password'] == sha1($userpass)) {   // do sensitive things here
    
    }
    

    Adding the shai1 to the ($userpass) gives an added bit of security to the session. Sha1 isn't a bulletproof method, but it's a nice barrier of security to keep malicious users at bay.

    8. Not Validating Cookie Data

    How much trust do you put into cookies? Most people don't think twice about the seemingly-harmless bit of data that's passed by a cookie. The name "cookie" itself is associated Milk, nap time and Santa, for crying out loud! How could a cookie possibly harmless?

    If you're not validating cookie data, you're opening your code to potential harmful data. You should use htmlspecialchars() or mysql_real_escape_string() to validate the cookie before storing it in a database.

    9. Not Escaping Entities

    Many times PHP programmers are too trusting with data, especially data generated by user. It's imperative to sanitize data before it goes into any sort of storage, like a database.

    Source Rally shows us how to correctly escape entities in things like forms. Instead of using this:

    echo $_GET['username'];
    

    You can validate the data by using htmlspecialchars() (or htmlentities()) like so:

    echo htmlspecialchars($_GET['username'], ENT_QUOTES);
    

    10. Using Wrong Comparison Operators

    While comparison operators are an extremely basic part PHP programming, mixing these up in your code is certain to bork your program. As the German proverb states, the Devil is in the details.

    Being familiar with the often-misused operators like =, ==, != , are absolutely critical to PHP programming. Taking the time to really understand the differences will greatly speed up your programming and yield less bugs to debug.



    Photo by Foxtongue.

    Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
    • http://www.zachstronaut.com/ Zachary Johnson

      If I had to list an 11th PHP Mistake, I would say it is using the PHP language construct empty() with string variables. You have to be careful with empty() because it returns true for the string value ’0′. More on the quirks of empty() here:

      http://www.zachstronaut.com/posts/2009/02/09/careful-with-php-empty.html

    • Pingback: Errores de PHP

    • Pingback: EgoGeek.com - 10 errores comunes al programar en PHP

    • Pingback: Antonio J. Balmón - Desde mi ventana » ¿ Cometes estos 10 errores en PHP ?

    • Clemens

      I’m with Anthony Bush. I’d like to add that you shouldn’t bench PHP and report the results, since they are highly dependant on the machine they are tested with. I got extremly variegated results for the performance of different loops on different machines for example. Fast on one computer means slow on others sometimes.

      This article ain’t all good. You’re basically teaching bad coding.

    • http://www.47ideas.com/ Tom Cameron

      Where to start with this article?! This was.. not good. Not good at all. For a start, there is no difference whatsoever (unless it’s due to the machine) between using double and single quotes. This has been proven in past tests. It’s personal preference really.

      Using htmlspecialchars() is okay, but hardly the best way to go about things. There are things that will be missed by this function; personally I’d prefer a combination of mysql_real_escape_string() and trim() to prevent these.

      And finally.. database caching. Unless you have a huge site this is not going to make a huge amount of difference; reccomending it for everybody is stupid. Plain and simple.

      Sorry for the negative tone of this review, but some of this article is just plain misinformation.

    • Andrew

      This tut is somewhat misleading. It should be re-written.

    • Pingback: Blog Desarrollo - Información para desarrolladores » Blog Archive » 10 errores que puedes estar comentiendo en PHP

    • Me Again

      For the life of me, I don’t understand how #7 is supposed to work. If you’re trying to prevent session hijacking you could save the IP and/or the user agent in the session and check it at every request. If you’re trying to prevent session fixation you should regenerate the session id (session_regenerate_id()) when the user logs in.

    • name 1

      half of this advice is wrong and outright awful.

    • Henrik Bjornskov

      Isnt this a bit late for a aprils first joke article ?

    • http://www.lampbuilder.com/ Marcel Esser

      This article is awful. If you’re learning PHP, please don’t read this; it’s littered with misleading information, and most of it is just useless. If you really want to learn to program PHP well, go get Advanced PHP Programming by Schlossnagle.

    • Kal-El

      I think you’ve confused validation with escaping/sanitation.

      htmlspecialchars, htmlentities, mysql_real_escape_string, et al. don’t validate anything. They escape/sanitize the evil characters so that you can feel somewhat safe in either inserting that data in a DB or outputting that data to the user.

      Validating means making sure what you are getting back from the user is what you are expecting. e.g. – If you’re expecting an integer value, type cast it to an int, or check it with is_int, and if it fails, send it back to the user to fix.

      As for #10, a good tip would not be “use the proper comparison operator”, but should rather be, “write your code in a way where, if you do mess up and use the wrong comparison operator, it will throw an error”.

      What this means is, if you mean == but write = in your loop conditions (or wherever), if you put the constant value first, your code will throw an error. Here is what I mean:

      while ($id = 1) // do something (except we meant $id == 1)

      That bit of code will fail silently, setting $id equal to 1, and continuing on. And because it’s in a while loop, it’s always true, and you’ve gotten yourself into an infinite loop.
      By reversing the sides of the equation, putting the constant first, we get the following:

      while (1 = $id) // do something (except we meant 1 == $id)

      This will throw an error, because you can’t set 1 equal to anything. You know immediately where the error is, and what needs to be done to fix it.

      I have never confused !=, ==, or = with anything else. I may have typed them wrong (and the impetus for using the constant first method above), or got my logic wrong on occasion, meaning and writing == when I should have used !=, but I have never accidentally typed != when I meant = or ==.

    • Concerned programmer

      Oh gee… This has to be the worst PHP article I have ever read… #9 takes the cake for total “braindeadness”… htmlspecialchars will not sanitize your content in any way… At least in no way an attacker won;t know how to completely bypass…

    • http://mihasya.com Mikhail P

      #11: Writing articles about PHP without knowing WTF you’re talking about.

      I think you are guilty of #11 there… It’s not really surprising you would have included it in your article, had you been aware of that particular pitfall.

    • http://www.capsule.org Thibaut Allender

      This really is for beginners or wong/alarming for beginners.

      SQL caching… Thank god, MySQL (the common DB companion for PHP) has some built-in caching.

      Once I did a benchmark between a caching method (based on files) and a no-cache one… guess what, the no-cache was faster!

      Caching DB on small or medium websites is OVERKILL.

      You should begin his article with “do not overkill!”

    • http://laurei.com Laurei

      Apart from the obvious which has been pointed out, I’ve found an interesting trend from the commenters on this post.

      a.) The amount of people who don’t read blog posts but still comment.
      b.) The amount of people who comment without actually reading, or at least skimming other comments to check that someone hasn’t just discredited the information they are commenting on, or that their comments already been said.

    • Pingback: 網站製作學習誌 » [Web] 連結分享

    • Pingback: Are You Making These 10 PHP Mistakes? - Nettuts+

    • http://www.aw3design.net astho

      #1 make me more confuse… hehehe…. ^^

    • michael

      #10 – don’t forget === particular with functions like strpos()
      i remember seeing a login script that allowed users to login by not specifying a password. this was easily fixed by changing the == operator to ===

    • Pingback: HTML, CSS, PHP and jQuery Killer Tutorials | Evan Mullins Circlecube ReBlog

    • http://www.la-munca.blogspot.com/ wappy

      #6. If yo’re using Apache it’s easier to “play” with .htaccess:
      php_value max_execution_time 200

    • http://quovadimusinteractive.com vidalstat

      What is the deal with all the flaming, hating on this post? Now I’ve never been accused of writing the most elegant code ever written, but I make a living–in New York City. I know, it’s a small market, not much in the way of web development, but we try. I find it hard to believe that you jerkoffs haven’t come across these sorts of mistakes in your career on a day-to-day basis.

      Do you code gurus speak to your project manager that way? That’s the problem with our industry today, I wish someone like Glen would come into my office and spread a little knowledge around. Is he perfect? No. It must be nice to crank out perfect, pretty code on deadline every day of the year.

      Maybe the rest of you should send in your l33t tutorials for our collective edification.

      you should be ashamed of yourselves.

    • Marcel Esser

      Actually, many of the people that commented to this thread have written books and articles on the topic.

      No one in the above claimed that their code was perfect, or any of that other non-sense you’re accusing people of. The fact of that matter is, very simply, that a lot of the advice was wrong or misleading.

    • http://www.phpreferencebook.com/ Mario

      Of course, E_ALL is important, as long as you can track down what PHP is telling you. I’d recommend for all the new PHP programmers to check out:
      http://www.phpreferencebook.com/misc/php-errors-common-mistakes/

      To help decode the PHP errors.

    • http://www.voizle.com/ Romeo

      nice article… DB cache is just superb

    • http://www.voizle.com/ Romeo

      Greate Article

    • Pingback: bulldoggie studio » 120 Tips, Tricks, and Tuts from 2009 Worth your Time

    • http://www.phpmycoder.net PhpMyCoder

      Great Article…one problem:

      Adding the shai1 to the ($userpass) gives an added bit of security to the session. Sha1 isn’t a bulletproof method, but it’s a nice barrier of security to keep malicious users at bay.

      Should be:

      Adding the sha1 to the ($userpass) gives an added bit of security to the session. Sha1 isn’t a bulletproof method, but it’s a nice barrier of security to keep malicious users at bay.

      (You wrote shai1 instead of sha1)

      Not a major problem, but I though you might want to know!

    • yousuck

      Agree with John. Anyone reading this is now more dumb. 7, 8 and 9 are absurd and the rest you should know BEFORE Programming 101.

    • http://www.helloworlder.com helloworlder

      I think to sanitize form data you must use mysql_real_escape_string(), and not htmlspecialchars()

      From the PHP manual “[mysql_real_escape_string] must always (with few exceptions) be used to make data safe before sending a query to MySQL.”

      • http://cv.zerkms.com zerkms

        Sanitizing is very different depending on what the data will be used for. For html the sanitizing is htmlspecialchars, for mysql – it is mysql_real_escape string (or, better, prepared statements). For plain files – it is nothing.

    • jmarreros

      thanks for sharing these tips

    • Pingback: dESiGNERz BLOG » 120 Tips, Tricks, and Tuts from 2009 Worth your Time

    • Pingback: De sju vanligaste PHP misstagen « ToggleOn – dit alla noder leder.

    • Pingback: 10 most common PHP Mistakes! « Itupdates4u’s Weblog

    • http://cv.zerkms.com zerkms

      The item 7 is just stupid.

      Nothing personal, but you have no idea what you’re talking about.

    • http://webfikirleri.com/ Murat

      Thanks much for this article.

    • http://allanmckee512.bravejournal.com/entry/81368 Akiko Tankson

      Heya i am for the first time here. I came across this board and I in finding It really helpful & it helped me out much. I’m hoping to provide one thing again and help others like you aided me.

    • Pingback: Are You Making These 10 PHP Mistakes? – Nettuts+ » Web Design

    • Pingback: Machst du diese 10 PHP Fehler? » netzmeisterleistung.de

    • http://wisnau.wordpress.com wisnau

      Thanks, great tips. May I copy-paste it for my blog?

    • David Zentgraf

      Re #7: Please tell me you’re not putting THE USER’S PASSWORD into a cookie to begin with! Please!

      A session cookie is simply PSEUDO RANDOM NOISE. It’s a meaningless value. It’s an opaque token. It doesn’t mean anything. It is only supposed to identify the user uniquely. You do not store any sensitive information in it like a password!