Common PHP Mistakes (and How to Avoid Them)

cover

PHP 8 removed some classic pitfalls and introduced a few new ones. Here are the mistakes we still see most often in real PHP code today, and how to fix each one.

Security mistakes

  1. Building SQL with string concatenation. Always use prepared statements with PDO or MySQLi. Never put $_GET or $_POST values straight into a query.
  2. Echoing user input without escaping. Use htmlspecialchars($value, ENT_QUOTES, 'UTF-8') on anything you output into HTML, or use a template engine that escapes by default.
  3. Storing passwords with md5() or sha1(). Use password_hash() and password_verify(). They handle salting and use a slow algorithm on purpose.
  4. No CSRF protection on forms. Any form that changes data should include a random token checked on submit.
  5. Trusting uploaded files. Check the real MIME type, rename the file, and store uploads outside the web root or in a folder where PHP execution is disabled.

Code quality mistakes

  1. Using == instead of ===. Loose comparison has surprising results. PHP 8 fixed the worst cases, but strict comparison is still the safe default.
  2. Suppressing errors with @. It hides bugs. Handle errors properly or let them surface in development.
  3. Showing errors in production. Set display_errors=Off and log_errors=On on live servers.
  4. Ignoring types. Add parameter and return types, and consider declare(strict_types=1);. They catch bugs before your users do.
  5. Not using Composer and autoloading. Manual require chains become unmanageable. Composer handles dependencies and class loading.

Performance and maintenance mistakes

  1. Running queries inside loops. Fetch the data you need in one query with a JOIN or an IN clause.
  2. Running an outdated PHP version. Old versions stop getting security fixes. Each new major version is also noticeably faster.
  3. No OPcache. Make sure it is enabled on the server. It is a free performance gain.
  4. Mixing logic and HTML everywhere. Separate data handling from presentation, even in small projects.
  5. Hard-coding credentials. Keep database passwords and API keys in environment variables or a config file outside version control.

A quick self-check

Search your codebase for mysql_query, md5(, @$ and string-built SQL. If you find any of them, that's where to start.

Comments