← PHP / Laravel · Contents

PHP-059 / Advanced

Regular expression ReDoS (catastrophic backtracking)

A04:2021 Insecure Design · CWE-1333 Inefficient Regular Expression Complexity

Why is this a problem?

A regular expression with nested quantifiers can occupy the CPU for seconds or longer with only a few hundred input characters.

How to fix it

php
preg_match('/^\w+(?:\s\w+)*$/', $text);  // Remove nesting and check length limits first
abort_if(strlen($text) > 500, 422);

Further reading