Courses

PHP Type Juggling with Loose Comparisons
OSWE · Chapter 12

PHP Type Juggling with Loose Comparisons

PHP's loose (`==`) comparison performs type juggling — automatically converting operand types before comparing — which produces surprising, exploitable results when comparing strings that look numeric, most famously in authentication and hash-comparison code.

Key concepts

  • A classic gotcha: `"0e123456" == "0e654321"` evaluates to `true` in loose comparison, because both strings are interpreted as scientific notation for zero — the basis of "magic hash" attacks.
  • The fix is simple but easy to forget: always use strict comparison (`===`) when comparing values whose type should matter, especially password hashes and tokens.
  • This bug class is PHP-specific in its exact mechanics, but every language with implicit type coercion (JavaScript's `==`, for instance) has analogous footguns.
  • Code review should specifically flag any `==` used for security-sensitive comparisons (password hash checks, HMAC/signature verification, session token comparison).

Example

<?php
var_dump("0e123456" == "0e654321"); // true — both parse as 0e... = 0
var_dump("0e123456" === "0e654321"); // false — strict comparison, correct

Try it yourself

In a local PHP REPL, test `var_dump("0e12" == "0e34")` and `var_dump("abc" == 0)` and explain in your own words why each result happens.

@ Daniel Burlacu