Common PHP Mistakes (and How to Avoid Them)
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
- Building SQL with string concatenation. Always use prepared statements with PDO or MySQLi. Never put
$_GETor$_POSTvalues straight into a query. - 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. - Storing passwords with md5() or sha1(). Use
password_hash()andpassword_verify(). They handle salting and use a slow algorithm on purpose. - No CSRF protection on forms. Any form that changes data should include a random token checked on submit.
- 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
- Using == instead of ===. Loose comparison has surprising results. PHP 8 fixed the worst cases, but strict comparison is still the safe default.
- Suppressing errors with @. It hides bugs. Handle errors properly or let them surface in development.
- Showing errors in production. Set
display_errors=Offandlog_errors=Onon live servers. - Ignoring types. Add parameter and return types, and consider
declare(strict_types=1);. They catch bugs before your users do. - Not using Composer and autoloading. Manual
requirechains become unmanageable. Composer handles dependencies and class loading.
Performance and maintenance mistakes
- Running queries inside loops. Fetch the data you need in one query with a JOIN or an IN clause.
- Running an outdated PHP version. Old versions stop getting security fixes. Each new major version is also noticeably faster.
- No OPcache. Make sure it is enabled on the server. It is a free performance gain.
- Mixing logic and HTML everywhere. Separate data handling from presentation, even in small projects.
- 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
Post a Comment