Get $500+ of the best After Effects files, video templates and music for only $20!

    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.

    Add Comment

    Discussion 111 Comments

    Comment Page 2 of 3 1 2 3
    1. JDub says:

      Encrypting your session ID won’t do anything. To prevent session hijacking, use session_regenerate_id(). This changes your session id periodically, while still associating your session information to you. If for some odd reason you actually want to dissociate your session information, you can pass a Boolean true to the function.

      If you’re serious about being a PHP programmer, study security. There is a certification program for this language, and you will learn a lot by studying for that too. There are far worse mistakes you can make than are in this list. If you are still making these mistakes, you are in trouble.

    2. @AgentSmith – I actually no longer even understand what he was trying to say. But the code looked wrong.

      To achieve the same results, you’d either do “hello $howdy”, or ‘hello ‘.$howdy

    3. kevin says:

      @Phd Pete, “using php is a mistake”, so what do you use? are you going to say “.net”. I think so. Stop making war. People already tired of it. I am using both php and c#. It is up to the programmers. Language does not matter. Just the logic inside your head is more important. If you use other languages except PHP, you don’t make any mistakes?
      If you are bad in one language, you will be bad in other languages as well. Don’t switch the language just because you can’t think right.

    4. Charlie says:

      After all the trouble to get the right code in #1 , it turns out that the supporting evidence that is linked to doesn’t actually support the author’s claim.

      It shows basically no difference in using single or double quotes from a speed perspective. If one were to pick a side based on the benchmarks there, one might actually claim that double quotes are faster.

    5. Wayne says:

      Thanks, great article! Btw, did anyone else mention that there might be a problem with #1? :P

    6. Kevin Martin says:

      Using single quotes is always best. According to many tests my peers and I have made. Double quotes take longer to process because they can also evaluate php variables within them. So:

      $a = ‘hello ‘ . $who;
      $b = “hello $who”;

      $a would be the way to go no matter what.

    7. Saeed Jabbar says:

      Good list. It depends on what your using single or double quotes for. If use single quotes only if you want literal strings or printing code.

    8. Darren says:

      I agree with Charlie and Thomas that #7 does nothing. I like Charlie’s suggestion about using environment variables as an extra check for session authenticity.

    9. lowell says:

      here’s one you missed:

      11. Using PHP.

    10. Matt says:

      To those of you saying, “Don’t use PHP”…

      PHP has evolved into a very robust, scalable language. As of version 5, advanced, well-structured OOP programming is quite possible — take a look at the Zend Framework, for example. PHP has gotten a bad rap because of years of misuse and the lack of one cohesive community that focuses on best practices. But, I think its versatility and the fact that it is used by many people for many different things is actually a good thing. Clearly there’s a need to make more people aware of how to write secure, optimized code. This article had some problems but it’s a step in the right direction.

      So quit with the PHP bashing… don’t blame the language, blame the programmers…

    11. whiskey says:

      There’s one missing though… parenthesis, logic operators and you (when applied to an if statement or anywhere else).

      if (!(($foo==$this) && ($bar==$that)))

      if ((($foo!=$this) || ($bar!=$that)))

      and such…

      I know, you are smiling… Either because it hasn’t happened to you just yet, or because it already did like the rest of us (when coding past your bedtime or CUI [coding under the influence]).

    12. Rebecca says:

      lowell!

      Why oh why would you want to use anything else?

      It’s the fastest, it’s easily found almost everywhere, it shouldn’t cost you a dime to set it up (software wise) and it does wonders.

      What language do you use then, lowell?

    13. John says:

      This is honestly one of the worst articles I’ve ever read. Among the applications that I support in an enterprise environment, 3 of them are PHP. 2 of them have no gain in using memcache. You don’t support any of your comments with facts or real explanation. Memcache will only help you if you’re regularly accessing the same data over and over.

      To comment on your “E_ALL” suggestion, it’s not a “STRICT” mode, it simply reports ALL (note the similarity in name) errors on the page. These errors are always occurring, it’s just that warnings are generally ignored since they’re only warnings.

      Two of your suggestions are simply language constructs. Not only are they avoidable by simply testing your code, but by using an IDE as well that will point out the error.

      7,8, and 9 make no sense at all. Why would you store something marked as a password in your session? How does mysql_real_escape_string have any impact on simply testing cookie data, in an app that may have no impact at all on the DB much less have any dependency on mysql. I think when you say “escape entities” you mean “escape request data.”

      And finally, =, ==, !=. Only two of those are comparison operators. This probably makes a third language construct issue. It should be fairly obvious to any programmer that != means Not Equals and == means equals. You make no mention of === which I find funny.

    14. Brent Lee says:

      @lowell
      Thanks for the super helpful tip.

    15. j-man says:

      I have to agree with John and Thomas (as well as the bulk majority of other commenters)

      Lots of incorrect information and conclusions here.

    16. Saeed Jabbar says:

      Matt’s evaluation is spot on especially in regards to having a unanimous community working towards improving PHP. PHP.net is a great attempt at this ,however it needs a major make over.PHP won’t be going away any time soon and as the language continues to develop it will become more standardize.Sorry for all the typos today , in a rush.

    17. marxx says:

      Thanks for this article!
      I’ll bet that these are mistakes what we all have done while we were beginners! :)

      And for all “You should do it like this..” or “that should be like this”, Maybe someone should write new article about those??
      Well, everyone has opinion and own style to do things so..

    18. Sagad says:

      Are you the nettuts? Is there technical editor?. Too many mislead.

    19. kevin says:

      For those people blaming on php,
      I saw some people had problems with php when they started learning web development, using php as their first choice.
      And then they moved on to another language and as they are having more and more experience with programming idea,logic , they are getting better in web development. Then they looked back and say “php is bad” as they had hard time learning it.
      I don’t mean everyone blaming php is like those people, just some of them are.

    20. terry chay says:

      #1 even if correct is no longer true. A lot of work has been done to get double quotes to perform nearly as fast as single quotes. I prefer single quotes myself, but if you benchmark, you’ll find no difference today between concatenation ‘hello ‘.$howdy and inline “hello $howdy”

      #7 is not correct either. The session idea will unlock the sha1… variable just as well. Look up Cross Site Request Forgery and Session Fixation. You are confusing things.

      The first security policy you are confusing this with using something akin to a nonce in order to prevent cross site request forgery. I’m of the opinion that using a session ID is just as good as generating something unique and storing it with the session, but many people do what you suggest and use that. Still a session ID, if hijacked is still hijacked.

      Another security policy you would need is to regenerate a new session ID on successful login in order to prevent session fixation. Luckily there is a command in PHP to do just that: session_regenerate_id

      The third security policy you need is that for data that is sensitive (like changing the password or purchasing a good) you have to rechallenge the user for their password (preferably behind SSL) because the session cookie has been passed back and forth during this time and is susceptible to hijacking via man in the middle.

      I hope this helps and good luck at learning PHP!

      Take care,

      terry

    21. Frank says:

      Hehe, it seems this article is pretty much useless.

    22. Susan says:

      Setting time limits is extremely important! Thanks for pointing that out.

    23. Mike says:

      John and Terry Chay do a pretty good job pointing out the flaws in this article. If you’re trying to learn php I would forget everything you just read pretty quickly. It seems the author recycled these tidbits of knowledge from sources he did not entirely understand. I don’t mean to bash as I learned tons from my mistakes writing similar articles but a technical editor should have identified some of these flaws before making it to a site like this.

      Glen Stansberry – Keep at it. If you’re interested in PHP security I would recommend APress’s book on the subject: http://www.amazon.com/Pro-PHP-Security-Chris-Snyder/dp/1590595084/
      The parts about data filtering, session, and cookie security are extremely useful.

    24. Haydar says:

      Thank you, i often make a mistake in 5 and 9
      5- i forget to remove E_ALL.
      9- Some times i forget to escape strings, but i am reviewing and fixing almost all the websites i have worked on for security bugs.

      I think every programmer must make a checklist to be checked after finishing programming, this will prevent us from making these mistakes again.

    25. Nick Ferrando says:

      Why don’t you user some scientific rigor in your articles?
      What the f… does “mistake” mean? ERROR?? Bad Practice? BUG??
      Not using memchached is not a “Mistake”, is just an option.

    26. Bad says:

      Newbies shouldn’t write articles.

    27. Adam says:

      This is the same guy who wrote this terrible article:

      http://www.smashingmagazine.com/2008/11/18/10-advanced-php-tips-to-improve-your-progamming/

      And got similar flack for it. I can’t stand his articles, and more importantly, I can’t stand that all of these big-time blogs somehow allow this guy to continue to post! ARGH

    28. Arnold Lemmon Pie says:

      yeah but ta pix are cewl!!

    29. Anthony Bush says:

      Please do not link to phpbench.com — some information there is wrong.

      It would appear to be a marketing exercise more than anything, which is unfortunate because now the PHP community suffers by its misinformation.

      e.g. the “Modify Loop” and “Read Loop” sections make incorrect use of the `reset()` function, which skews the results (not to mention that the results are calculated live on every page load).

      WRONG: “it’s extremely good to use the reset() function in all examples” — you should NOT use reset() before a foreach loop as this is done for you and using it only slows execution.

    30. Well, I’m very happy with my code, cause of every mistake that you talked about I’m not making any of them in my PHP code.

    31. 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

    32. Clemens says:

      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.

    33. Tom Cameron says:

      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.

    34. Andrew says:

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

    35. Me Again says:

      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.

    36. name 1 says:

      half of this advice is wrong and outright awful.

    37. Henrik Bjornskov says:

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

    38. Marcel Esser says:

      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.

    39. Kal-El says:

      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 ==.

    40. Concerned programmer says:

      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…

    41. Mikhail P says:

      #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.

    42. 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!”

    43. Laurei says:

      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.

    44. astho says:

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

    45. michael says:

      #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 ===

    46. wappy says:

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

    47. vidalstat says:

      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.

    48. Marcel Esser says:

      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.

    49. Mario says:

      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.

    Comment Page 2 of 3 1 2 3

    Add a Comment

    To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.