---
title: Avoid Eval Or Dynamic Code Execution
impact: HIGH
impactDescription: prevents remote code execution vulnerabilities
tags: eval, code-execution, rce, injection, security, php
---

## Avoid Eval Or Dynamic Code Execution

`eval()`, `exec()`, `system()`, and similar functions execute arbitrary code or shell commands. Using these with user-controlled input makes the application extremely vulnerable to Remote Code Execution (RCE).

**Incorrect (dynamic code execution):**

```php
// eval() with user input
$formula = $_POST['formula'];
eval('$result = ' . $formula . ';');  // RCE vulnerability!

// system() or exec() with unsanitized input
system("ls -l " . $_GET['dir']); // Command injection!

// create_function() with user input (Deprecated)
$func = create_function('$a', 'return ' . $_POST['logic'] . ';');

// Dangerous unserialize with user input
$data = unserialize($_POST['data']); // Object injection vulnerability
```

**Correct (safe alternatives):**

```php
// Use a dedicated library for expression parsing (e.g., symfony/expression-language)
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;

$expressionLanguage = new ExpressionLanguage();
$result = $expressionLanguage->evaluate($formula, ['a' => 10]);

// Use an allowlist for commands
$allowedDirs = ['uploads', 'public'];
$dir = $_GET['dir'];
if (in_array($dir, $allowedDirs)) {
    $safeDir = escapeshellarg($dir);
    system("ls -l " . $safeDir);
}

// Use JSON for data exchange (instead of serialize)
$data = json_decode($_POST['data'], true);

// For dynamic inclusion, use an allowlist
$allowedPages = ['home', 'contact', 'about'];
$page = $_GET['page'];
if (in_array($page, $allowedPages)) {
    require_once "pages/" . $page . ".php";
}
```

**Tools:** PHPStan (disallow-eval), Psalm, SonarQube (S1523), Semgrep
