Unsafe preg_replace usage

Rejah Rehim
Published on
24 Jun 2018

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.
Automated human-like penetration testing for your web apps & APIs
Teams using Beagle Security are set up in minutes, embrace release-based CI/CD security testing and save up to 65% with timely remediation of vulnerabilities. Sign up for a free account to see what it can do for you.

Written by
Rejah Rehim
Rejah Rehim
Co-founder, Director
Find website security issues in a flash
Improve your website's security posture with proactive vulnerability detection.
Free website security assessment