PHP Type Juggling
Vulnerabilities from PHP's loose type comparisons where automatic type conversion can lead to authentication bypasses using "magic hash" values.
PHP Type Juggling is a vulnerability arising from PHP's loose type comparison system, where values of different types are automatically converted for comparison, potentially leading to authentication bypasses and other security issues.
How Type Juggling Works
# Loose comparison (==) does type coercion
# NOTE: PHP < 8.0 behavior. In PHP 8+, "abc" == 0
# and "1abc" == 1 are both false (see below).
"0" == 0 // true (string converted to int)
"abc" == 0 // true (non-numeric string = 0)
"0e123" == 0 // true ("scientific notation" = 0)
"1abc" == 1 // true (leading number extracted)
true == "any" // true (non-empty string = true)
null == "" // true
PHP 8.0+ Changes
Important: PHP 8.0 changed string-to-number comparison behavior. The "0e" magic hash trick no longer works in PHP 8+ because non-numeric strings are no longer coerced to 0. However, type juggling issues still exist with:
- Comparisons between numeric strings:
"0" == "0.0"is still true - Boolean comparisons:
true == "anystring"is still true - JSON input where attacker controls type:
{"password": true}
Prevention
- Use strict comparison (
===) not loose (==) - Use
hash_equals()for hash comparisons - Validate input types explicitly
- Use JSON schema validation