php gotchas: 10 common pitfalls and how to avoid them

A beginner's guide to PHP and its common pitfalls.

Especially for web development, PHP is one of the most popular general-purpose scripting language that has been widely used as a framework and especially suitable for use with Web Development.

10 common gotchas in php

  1. Loose Type Comparisons

    • Using == instead of === can lead to unexpected results due to type juggling.
    1
    2
    
    var_dump(0 == 'foo');   // true
    var_dump(0 === 'foo');  // false
    
  2. Uninitialized Variables

    • Accessing variables before assignment does not throw errors, but returns null.
    1
    
    echo $x; // null, no error
    
  3. Global Variables in Functions

    • Variables are not global inside functions unless declared with global.
    1
    2
    3
    4
    5
    
    $a = 1;
    function test() {
      global $a;
      echo $a;
    }
    
  4. Array Indexing

    • PHP arrays are ordered maps, and mixing numeric and string keys can be confusing.
    1
    2
    
    $arr = [0 => 'a', '1' => 'b', 2 => 'c'];
    print_r($arr);
    
  5. Magic Quotes and Deprecated Features

    • Some older features are deprecated or removed; always check your PHP version.
    1
    2
    
    // magic_quotes_gpc is removed in PHP 5.4+
    // Use filter_input() or prepared statements instead
    
  6. Case Sensitivity

    • Variable names are case-sensitive, but function names are not.
    1
    2
    3
    4
    
    $foo = 1;
    echo $Foo; // undefined variable
    function test() { return 1; }
    echo TEST(); // works
    
  7. Session Handling

    • Forgetting to call session_start() before using sessions causes issues.
    1
    2
    3
    
    // Always call session_start() before accessing $_SESSION
    session_start();
    $_SESSION['user'] = 'admin';
    
  8. Error Reporting Levels

    • Not setting error reporting can hide bugs during development.
    1
    2
    
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
  9. Include/Require Paths

    • Relative paths can break includes; use absolute paths or __DIR__.
    1
    
    include __DIR__ . '/file.php';
    
  10. Superglobals Scope

    • Superglobals like $_POST are always available, but may not be populated as expected in CLI scripts.
    1
    2
    
    // $_POST is empty when running from CLI
    print_r($_POST);
    

What should I keep in mind to avoid common pitfalls when working with PHP!

Built with Hugo
Theme Stack designed by Jimmy