๐ญ๐ฌ ๐๐ผ๐บ๐บ๐ผ๐ป ๐ฃ๐๐ฃ ๐๐๐ด๐ ๐๐ป ๐ฅ๐ฒ๐ฎ๐น-๐ง๐ถ๐บ๐ฒ ๐๐ฒ๐๐ฒ๐น๐ผ๐ฝ๐บ๐ฒ๐ป๐
PHP is a forgiving language. That forgiveness makes it dangerous in production.
Your code works locally. Code reviews pass. Then a silent bug hits your live server. These are not textbook errors. These are real bugs from login systems, e-commerce sites, and client projects.
Here are 10 common PHP bugs and how to fix them.
- Variable Scope The variable $username is defined outside a function. It is not accessible inside.
- Fix: Pass the variable as a parameter.
- Why: PHP functions have isolated scope.
- Assignment vs Comparison Using if($isLoggedIn = true) assigns a value instead of checking it. This always returns true.
- Fix: Use if($isLoggedIn === true).
- Why: The = operator assigns a value. The === operator compares both value and type.
- UTF-8 Character Counting strlen() counts bytes. For UTF-8 text like "เคจเคฎเคธเฅเคคเฅ", it returns 18 instead of 6.
- Fix: Use mb_strlen($text, 'UTF-8').
- Why: UTF-8 characters use multiple bytes.
- Missing isset() Check Accessing $_POST['username'] before a form submits causes an undefined index error.
- Fix: Use if(isset($_POST['username'])) or the null coalescing operator: $name = $_POST['username'] ?? '';
- Plain Text Passwords Storing passwords as raw text is a massive security risk.
- Fix: Use password_hash() with BCRYPT and verify with password_verify().
- SQL Injection Putting user input directly into a query string allows attackers to dump your database.
- Fix: Use PDO prepared statements.
- Why: Prepared statements treat input as data, not as part of the SQL command.
- Redirect without exit() The header() function sets a redirect but does not stop the script. The server keeps running the code below it.
- Fix: Always call exit() after a header redirect.
- Large File Memory Crashes file_get_contents() loads the entire file into RAM. This crashes your server on large files.
- Fix: Use fopen() and fgets() to read files line by line.
- Session Errors Calling session_start() after you have already sent HTML or whitespace to the browser causes errors.
- Fix: Put session_start() at the very top of your file.
- Silent Database Errors By default, PDO can fail silently without telling you why.
- Fix: Set PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION.
- Why: This turns failures into exceptions you can catch and log.
Stop these bugs by following three habits:
- Always validate input.
- Always handle errors explicitly.
- Always escape output.
Source: https://dev.to/bikkisingh/10-common-php-bugs-in-real-time-development-with-fixes-1lf7