Unsafe preg_replace usage

OWASP 2013-A9 OWASP 2017-A9 OWASP 2021-A6 CWE-661 WASC-13

The preg_replace is a function present in the PHP language to perform search and replace. The preg_replace is an obsolete function in PHP which can have major consequences in certain situations. An attacker can easily use the preg_replace function to perform attacks on the server to access sensitive information. The attacker uses the ‘e’ modifier to the preg_replace function to make the replaced content executable in PHP. Using this modifier, the attacker can execute any PHP functions to attack inside the server. Consider if the user controls the regex pattern and the replacement string parameter, the attacker will be able to perform PHP code execution attack.


The below code will output the contents of passwd. Leaking this information can have catastrophic impacts on the application.

        preg_replace("/.*/e","system('echo /etc/passwd')");



The major impacts include:-

  • Malicious code execution
  • Possible information leakage

Mitigation / Precaution

  • Beagle recommends avoiding the usage of preg_replace in the application.

Latest Articles