Common PHP Mistakes

I was recently asked by one of my readers to give feedback on the following article he read: 10 Most Common PHP Mistakes. It is well written and very thorough. Most of the tips are specific to PHP, others are about web programming in general or database performance. It’s a very good read. I was also asked to contribute to this list, so here are 7 more tips. I found these very common in my code reviews or various audits.

11. Forgetting to cache

Websites can be slow due to a variety of reasons. Adding a cache layer not only improves the user’s experience, but also tremendously reduces the load on your servers. There are many ways to cache and you can combine different cache types: query cache, Redis, Varnish, etc.

12. Allowing SQL injection

Security is easy to overlook, especially when starting out. SQL injections are extremely dangerous. Let’s say you write this in your code:

It is possible for the user to provide a malicious input, such as:

Once your query is concatenated, it will end up looking like this:

You can protect yourself by filtering the input, such as making sure that it’s a number. Another good practice is to always use prepared statement when using PHP variables in SQL. Example:

This will make sure that a user simply cannot “break” out of the query. More on prepared statements.

13. Disabling error reporting

When I first started writing PHP in 2003, I was annoyed when my PHP errors or notices showed up on the web. I simply disabled error reporting in production, while keeping them on my local machine to help debug my code. This was a mistake. If any error should happen in production, the user won’t see it, but I won’t know that something is broken either. For this purpose, you should keep the error reporting. Don’t show it to the user but log it to a file, which you can then view. This can be done easily via the php.ini file:

14. Staying on the same page after the form was processed

If the form contains errors, you will probably display the same page again and highlight the errors. That’s good. But then if the form was successful and processed, such as creating a database record or charging a credit card, you need to redirect the user. Think of it as adding sugar to your coffee. Each time you refresh the page (your user can choose to accept the resubmit warning), another spoon of sugar is added. Do it enough times and you’ll have sugar with a hint of coffee, or charge the credit card 10 times. Redirecting the user lets you prevent “replaying” the action. Redirect like this:

15. Reinventing the wheel

The PHP community is incredibly active. There are countless packages that you can install using Composer. Tools include e-mailing, file system, templating, caching, parsing various formats, handling multilingualism, unit testing, etc.

Many people don’t realize how many functions come out of the box with PHP. There are thousands of functions that can replace hundreds (or more) of lines in your code, so dig around.

There are also many frameworks that help you organize your code and take a lot of the repetitive, tedious work off your hands. Find a top X list, read some reviews on each and take a pick.

16. Letting your scripts run forever

Don’t assume that your script will always finish quickly. Perhaps your script talks to a server that is taking long to respond. Perhaps the user decided to upload a very big file. Perhaps you have a database congestion and your script is just waiting on its turn. Expect the unexpected and use set_time_limit().

Extra trick: determine which scripts should be lighting quick, such as upvoting a comment, and which should be allowed to run longer, such as image processing. Set a time limit based on expected maximum. If there is an unexpected delay, your script will fail (and log an error). Your server won’t be overwhelmed, your user won’t wait for no good reason (a negative answer is better than no answer at all) and you will also have a log to tell you that something needs fixing.

It’s still a good idea to write safeguard in your code, such as checking upload size or setting timeouts on API requests.

17. Ignoring accessibility

What is it? Accessibility is basically making sure that everyone can use your site despite any limitations. To list but a few: can’t distinguish some colors, can’t see small font, can’t see, no fingers, arthritis, multiple sclerosis (even I will forget what was the first menu item if you have 25 of them), etc. I personally know people from each category. Accessibility also applies to the range of devices. Basically, embrace the diversity and design for inclusion.

I recommend a reporting tool such as Wave. Give it a spin. It makes accessibility easy and fun.

Add more tips in the comments! In case you wonder about the image, it’s a pressure barrel (beer).

4 thoughts on “Common PHP Mistakes

  1. Some of the big ones I’ve had to learn…

    C1. Test for large amounts of data

    Your simple querying may work fine for 10 entries, or even 50 — what if there are suddenly 5000 put into the system? If this could happen, test it, to ensure you correctly place CMS limits, runtime limits, or implement efficient pagination. Having your code being “unlimited” usually just shows you haven’t actually thought about how to control scaling factors.

    C2. Don’t make overly-complex array structures for routine tasks

    PHP uses a lot of memory to store variables. If you have really complex array structures containing a lot of data, it will consume huge amounts of memory for a relatively much smaller amount of domain data. Don’t underestimate the over-head of PHP as a dynamic loosely-typed language.

    C3. Learn regular expressions early in your career

    Often 20 lines of code can be replaced with a relatively simple regular expression.

    C4. Remember to lock files

    I was certainly guilty of having over-confidence in how well-constructed and robust computers are. Be warned that they do not automatically lock files and sit around waiting for locks to become free. If you have two processes potentially writing the same file, you need to write to write quite a lot of careful flock code in PHP if you don’t want them to mangle the file.

    C5. Thumbnailing takes RAM

    If you’re generating thumbnails, and a user uploads an enormous compressed image, be aware it uses the amount of RAM that image would be uncompressed, in order to generate the thumbnail. This could easily take a server down if you don’t put in some guards.

    C6. MySQL MyISAM locks on a table-level, Apache can crash

    MyISAM uses table-level locks. This means if a slow read is happening on a table, a write cannot happen until it finishes. If you have high write-contention, you can get quite a long request tool blocking up. Each request in the pool uses RAM. If your system RAM is exceeded, disk swapping happens. If disk swapping happens, all performance declines. This can quickly create an exponential drop off in performance, and completely crash and lock you out of a server, forcing a hard-reset.

    C7. Database indexes are important

    Similar to earlier, don’t assume computers are smart. Classic algorithms are not necessarily applied automatically. You need to create database indexes if you wish to query upon a particular field, else your database will need to search all table rows in full sequence, to find matches. Don’t just index everything though, as this will waste disk space and slow down database rights. You need to use proper consideration on what exactly needs to be indexed.

    C8. Don’t gloss over detail

    We can generalise C7 to say that it can be easy to ignore key parts of a framework that you initially get away without needing. At some point try and learn the systems you’re doing in more detail, rather than just little parts. Not right at first, as it will overwhelm you, but don’t forget to do it.

  2. PP

    17 is not a PHP mistake, thats about client side stuff 😉

    • You are correct, accessibility is a front-end issue. I was hesitant to add it too. The reason I added it is because a lot of PHP developers are also responsible for the HTML layer, especially in smaller corporations. It’s an important topic and it’s difficult to expose developers to it. Hopefully, PHP developers who read my article will click the link and give Wave a spin.

  3. dedra

    Hello! It’s therefore crucial to recognize when queries are being made, either directly or indirectly, by your code. Whenever possible, gather the values and then run one query to fetch all the results. Yet caution must be exercised there as well, which leads us to our next common PHP mistake… By the way the best paper writing service that I saw:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">