eval

suggest change

eval() takes a string and runs it as PHP code, at run time, in the current scope:

eval('echo "Hello from eval\n";');

It is a language construct, not a function, and it is the most dangerous construct in PHP. If any part of the string comes from a user, the user can run arbitrary code on your server. The PHP manual itself says: if you have decided to use eval(), think again.

This article shows how eval() behaves (scope, return values, errors), why it is dangerous, and what to use instead. Its use is so rare in modern PHP that knowing the alternatives matters more than knowing eval() itself.

Basic usage and return values

The string must be valid PHP code without the opening <?php tag, and each statement must end with a semicolon. eval() returns null unless the code executes a return statement:

<?php
$result = eval('return 2 + 3 * 4;');
var_dump($result);

$nothing = eval('$x = 10;');
var_dump($nothing);
var_dump($x);

eval('echo "Hello from eval\n";');

eval('?>Plain text, then <?= strtoupper("php") ?> again' . "\n");

Output:

int(14)
NULL
int(10)
Hello from eval
Plain text, then PHP again

The code starts in PHP mode. Starting it with ?> switches to HTML mode, just like in a template file.

Scope: eval'd code sees your variables

The code runs in the scope where eval() is called. It can read and modify local variables, and variables it creates stay around afterwards. Functions and classes it declares are global, just like ones declared in an included file:

<?php
function demo(): void
{
    $price = 100;
    eval('$price *= 1.2; $tax = $price - 100;');
    echo "price: $price, tax: $tax\n";
}
demo();

eval('function greet(string $name): string { return "Hi, $name"; }');
eval('class Point { public function __construct(public int $x = 0, public int $y = 0) {} }');

echo greet('Ann'), "\n";
var_dump(new Point(1, 2));
var_dump(function_exists('greet'));

Output:

price: 120, tax: 20
Hi, Ann
object(Point)#1 (2) {
  ["x"]=>
  int(1)
  ["y"]=>
  int(2)
}
bool(true)

This is why eval() is so powerful and so dangerous: the code has the same access as the code around it, including database connections, secrets in variables and the file system. See Variable scope for how scope works in general.

Quoting: use nowdoc for the code

A common bug is building the code string in double quotes. PHP interpolates variables into the string before eval() sees it, so $name in the code becomes the variable's value, not a variable reference. Escape the $ or, better, use a nowdoc (<<<'PHP'), which passes the text verbatim:

<?php
$name = 'outer';

// Double quotes: $name is interpolated BEFORE eval runs
eval("\$greeting = 'Hello, $name';");
echo $greeting, "\n";

// Nowdoc: the code is passed to eval verbatim
$code = <<<'PHP'
    $name = strrev($name);
    return "Hello, $name";
    PHP;
echo eval($code), "\n";
echo $name, "\n";

Output:

Hello, outer
Hello, retuo
retuo

The first eval() works only by accident: if $name contained a ', the generated code would be a syntax error, or worse, valid code doing something else. This is exactly how code injection happens.

Errors in eval'd code

Since PHP 7, a syntax error in the string throws a ParseError instead of killing the script, so you can catch it:

<?php
$snippets = [
    'return 1 +;',
    'return strlen("abc");',
    'echo "missing semicolon"',
];

foreach ($snippets as $code) {
    try {
        $value = eval($code);
        echo "ok: ", var_export($value, true), "\n";
    } catch (ParseError $e) {
        echo "ParseError: ", $e->getMessage(), " on line ", $e->getLine(), "\n";
    }
}

Output:

ParseError: syntax error, unexpected token ";" on line 1
ok: 3
ParseError: syntax error, unexpected end of file, expecting "," or ";" on line 1

Exceptions and errors thrown while the code runs propagate to the caller like any others. Inside eval'd code, __FILE__ and getFile() report a pseudo file name that includes the file and line of the eval() call, and line numbers count from the start of the string:

<?php
try {
    eval('throw new RuntimeException("from inside eval");');
} catch (RuntimeException $e) {
    echo $e->getMessage(), "\n";
    echo basename($e->getFile()), "\n";
    echo $e->getLine(), "\n";
}

try {
    eval('return intdiv(1, 0);');
} catch (DivisionByZeroError $e) {
    echo get_class($e), ": ", $e->getMessage(), "\n";
}

eval('echo basename(__FILE__), " line ", __LINE__, "\n";');

Output:

from inside eval
a4.php(3) : eval()'d code
1
DivisionByZeroError: Division by zero
a4.php(16) : eval()'d code line 1

When you see eval()'d code in a stack trace or error log, it tells you where the eval() call is.

Some errors are still fatal and can't be caught. Declaring the same function or class twice ends the script:

<?php
eval('function helper() { return 1; }');
try {
    eval('function helper() { return 2; }');
} catch (Throwable $e) {
    echo "caught ", get_class($e), "\n";
}
echo "after\n";

Output (paths shortened):

Fatal error: Cannot redeclare function helper() (previously declared in ...\b1.php(2) : eval()'d code:1) in ...\b1.php(4) : eval()'d code on line 1

Neither caught nor after is printed. Guard declarations with function_exists() or class_exists().

Why eval is dangerous: code injection

Here is a typical "calculator" that evaluates a math expression from the query string:

<?php
// simulate request: ?expr=...
$_GET['expr'] = '2 * 21';
echo eval('return ' . $_GET['expr'] . ';'), "\n";

$_GET['expr'] = 'php_uname("s") . " " . PHP_VERSION';
echo eval('return ' . $_GET['expr'] . ';'), "\n";

Output:

42
Windows NT 8.5.11

The second request shows the problem. The "expression" is any PHP code. Instead of php_uname() an attacker sends system("..."), file_get_contents(".env") or code that installs a web shell. This is remote code execution, the worst kind of vulnerability a web application can have.

Things that do not make this safe:

The same applies to other ways of turning data into code: include of a user-controlled path (see File Inclusion), preg_replace with the /e modifier (removed in PHP 7) and create_function() (removed in PHP 8). Passing user data to a shell is the same problem one level lower; see Command Line Injection.

The only safe rule: never pass untrusted input into eval(), not even part of it.

Alternatives to eval

Almost every use of eval() in old PHP code has a better replacement.

Dynamic names: variable functions, methods and properties

Old code often built code strings just to call a method whose name was in a variable. PHP can do this directly. Combine it with an allow-list when the name comes from a request:

<?php
class Report
{
    public function daily(): string { return 'daily report'; }
    public function weekly(): string { return 'weekly report'; }
}

$action = 'weekly';           // e.g. from $_GET['action']
$field = 'total';

// Bad: eval('$out = (new Report)->' . $action . '();');

// Good: a dynamic method call, restricted to an allow-list
$allowed = ['daily', 'weekly'];
if (in_array($action, $allowed, true)) {
    echo (new Report)->$action(), "\n";
}

// Dynamic function name
$fn = 'strtoupper';
echo $fn('dynamic call'), "\n";

// Callable array, invoked with arguments from an array
echo call_user_func_array([new Report, 'daily'], []), "\n";

// Dynamic property and array key instead of building code
$data = ['total' => 99];
$obj = new stdClass();
$obj->$field = $data[$field];
echo $obj->total, "\n";

// A table of closures instead of generated code
$ops = [
    'add' => fn(int $a, int $b) => $a + $b,
    'mul' => fn(int $a, int $b) => $a * $b,
];
echo $ops['mul'](6, 7), "\n";

Output:

weekly report
DYNAMIC CALL
daily report
99
42

More on these in Callable, Closures and Accessing a variable dynamically by name.

Data: use a data format, not PHP literals

Don't store data as PHP array literals and eval() it back. Use JSON (or another real data format) and parse it:

<?php
$text = "['host' => 'localhost', 'port' => 5432]";
// Bad: $config = eval("return $text;");

$json = '{"host": "localhost", "port": 5432}';
$config = json_decode($json, true, flags: JSON_THROW_ON_ERROR);
var_dump($config);

Output:

array(2) {
  ["host"]=>
  string(9) "localhost"
  ["port"]=>
  int(5432)
}

A parser only builds values. It can never call a function. For PHP objects, avoid unserialize() on untrusted data too; see Security Issues with unserialize.

Cached PHP code: write a file and include it

Frameworks do generate PHP code, for compiled templates, configuration caches and dependency injection containers. They write it to a file and require it instead of calling eval(). Included files are cached by OPcache, while eval'd code is compiled again on every call. var_export() produces a valid PHP literal from a value:

<?php
$config = ['host' => 'localhost', 'port' => 5432, 'debug' => false];

$file = sys_get_temp_dir() . '/config.cache.php';
$tmp = $file . '.' . bin2hex(random_bytes(4));
file_put_contents($tmp, '<?php return ' . var_export($config, true) . ";\n");
rename($tmp, $file);   // atomic replace, readers never see a half-written file

echo file_get_contents($file);
$loaded = require $file;
var_dump($loaded === $config);
unlink($file);

Output:

<?php return array (
  'host' => 'localhost',
  'port' => 5432,
  'debug' => false,
);
bool(true)

The generated file can also be checked with php -l, read in an editor and stepped through in a debugger, none of which works well for a string passed to eval(). Make sure the cache directory isn't writable by anyone who shouldn't be able to run code.

Expressions from users: write a small parser

If users really need to enter formulas, evaluate them with a parser that understands only the operations you allow. A recursive descent parser for arithmetic fits in a page:

<?php
// Evaluates + - * / and parentheses on numbers. Nothing else is accepted.
final class Calculator
{
    private array $tokens = [];
    private int $pos = 0;

    public function evaluate(string $expr): float
    {
        if (!preg_match_all('/\d+(?:\.\d+)?|[-+*\/()]|\S/', $expr, $m)) {
            throw new InvalidArgumentException('empty expression');
        }
        $this->tokens = $m[0];
        $this->pos = 0;
        $value = $this->sum();
        if ($this->peek() !== null) {
            throw new InvalidArgumentException("unexpected '{$this->peek()}'");
        }
        return $value;
    }

    private function peek(): ?string
    {
        return $this->tokens[$this->pos] ?? null;
    }

    private function next(): ?string
    {
        return $this->tokens[$this->pos++] ?? null;
    }

    private function sum(): float
    {
        $v = $this->product();
        while (in_array($this->peek(), ['+', '-'], true)) {
            $v = $this->next() === '+' ? $v + $this->product() : $v - $this->product();
        }
        return $v;
    }

    private function product(): float
    {
        $v = $this->factor();
        while (in_array($this->peek(), ['*', '/'], true)) {
            $op = $this->next();
            $rhs = $this->factor();
            if ($op === '/' && $rhs == 0) {
                throw new DivisionByZeroError('division by zero');
            }
            $v = $op === '*' ? $v * $rhs : $v / $rhs;
        }
        return $v;
    }

    private function factor(): float
    {
        $t = $this->next();
        if ($t === '-') {
            return -$this->factor();
        }
        if ($t === '(') {
            $v = $this->sum();
            if ($this->next() !== ')') {
                throw new InvalidArgumentException("expected ')'");
            }
            return $v;
        }
        if ($t === null || !is_numeric($t)) {
            throw new InvalidArgumentException("unexpected '" . ($t ?? 'end') . "'");
        }
        return (float) $t;
    }
}

$calc = new Calculator();
foreach (['2 * 21', '(1 + 2) * -3.5', '10 / 4 - 1', '1 / 0', 'php_uname("s")'] as $expr) {
    try {
        $result = $calc->evaluate($expr);
        printf("%-16s = %s\n", $expr, $result);
    } catch (InvalidArgumentException | DivisionByZeroError $e) {
        printf("%-16s ! %s\n", $expr, $e->getMessage());
    }
}

Output:

2 * 21           = 42
(1 + 2) * -3.5   = -10.5
10 / 4 - 1       = 1.5
1 / 0            ! division by zero
php_uname("s")   ! unexpected 'p'

The injection attempt is just an unexpected token. For variables, functions and comparisons, use a library such as symfony/expression-language, which parses its own small language and only calls functions you register.

When eval is acceptable

There are a few legitimate uses, all of them with code the program generates itself, never with user input:

If you generate code, build it from validated pieces. Check that every name inserted into the code is a valid identifier, and never insert raw values; insert var_export($value, true) instead:

<?php
function defineRecord(string $class, array $fields): void
{
    $ident = '/^[A-Za-z_][A-Za-z0-9_]*$/';
    foreach ([$class, ...$fields] as $name) {
        if (!preg_match($ident, $name)) {
            throw new InvalidArgumentException("invalid identifier: $name");
        }
    }
    if (class_exists($class, false)) {
        return;   // already defined, eval would be a fatal error
    }

    $params = implode(', ', array_map(fn($f) => "public readonly mixed \$$f", $fields));
    $code = "final class $class { public function __construct($params) {} }";
    echo $code, "\n";
    eval($code);
}

defineRecord('User', ['id', 'email']);
defineRecord('User', ['id', 'email']);   // second call is a no-op

$u = new User(7, 'ann@example.com');
echo $u->id, ' ', $u->email, "\n";

try {
    defineRecord('Evil', ['x) {} } system("calc"); class Y { function f(']);
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(), "\n";
}

Output:

final class User { public function __construct(public readonly mixed $id, public readonly mixed $email) {} }
7 ann@example.com
invalid identifier: x) {} } system("calc"); class Y { function f(

Even here, an anonymous class (new class(...) { ... }) or a generic class with an array of values often makes the generated code unnecessary.

Limiting what eval'd code can see

Wrapping eval() in a static closure gives the code a fresh scope, so it can't read or overwrite the caller's local variables:

<?php
// Run evaluated code in its own scope by wrapping it in a closure
function evalIsolated(string $code, array $vars = []): mixed
{
    return (static function () {
        extract(func_get_arg(1));
        return eval(func_get_arg(0));
    })($code, $vars);
}

$secret = 'do not touch';
echo evalIsolated('return $a + $b;', ['a' => 2, 'b' => 3]), "\n";
var_dump(evalIsolated('return isset($secret);'));

Output:

5
bool(false)

This avoids accidental clobbering of variables. It is not a sandbox: the code can still call any function, use $GLOBALS, read files and open network connections. PHP has no built-in way to run untrusted code safely.

Checking syntax without running code

To validate generated code before running it, use token_get_all() with the TOKEN_PARSE flag. It throws ParseError for invalid code and executes nothing:

<?php
function isValidPhp(string $code): bool
{
    try {
        token_get_all('<?php ' . $code, TOKEN_PARSE);
        return true;
    } catch (ParseError $e) {
        echo "  ", $e->getMessage(), "\n";
        return false;
    }
}

var_dump(isValidPhp('echo "hi";'));
var_dump(isValidPhp('echo "hi"'));
var_dump(isValidPhp('unlink("/etc/passwd");'));

Output:

bool(true)
  syntax error, unexpected end of file, expecting "," or ";"
bool(false)
bool(true)

The last line is a reminder that "valid" doesn't mean "safe".

Removed eval-like features

Older code and tutorials use features that evaluated strings implicitly. They are gone in modern PHP:

Feature Status Replacement
create_function('$a', 'return $a * 2;') removed in PHP 8.0 fn($a) => $a * 2
preg_replace('/.../e', ...) removed in PHP 7.0 preg_replace_callback()
assert('$x > 0') with a string string no longer evaluated since PHP 8.0 assert($x > 0)
mb_ereg_replace() with the e option removed in PHP 8.0 mb_ereg_replace_callback()

In PHP 8, a string passed to assert() is just a non-empty string, which is truthy, so assert('1 + 1 === 3') passes silently. Pass an expression, not a string.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents