1.2.429. Eval() Usage

Using eval() is evil.

Using eval() is bad for performances (compilation time), for caches (it won’t be compiled), and for security (if it includes external data). Most of the time, it is possible to replace the code by some standard PHP, like variable variable for accessing a variable for which you have the name. At worse, including a pregenerated file is faster and cacheable.

There are several situations where eval() is actually the only solution :

For PHP 7.0 and later, it is important to put eval() in a try..catch expression.

<?php
    // Avoid using incoming data to build the eval() expression : any filtering error leads to PHP injection
    $mathExpression = $_GET['mathExpression'];
    $mathExpression = preg_replace('#[^0-9+-*/(/)]#is', '', $mathExpression); // expecting 1+2
    $literalCode = '$a = '.$mathExpression.';';
    eval($literalCode);
    echo $a;

    // If the code code given to eval() is known at compile time, it is best to put it inline
    $literalCode = 'phpinfo();';
    eval($literalCode);

?>

See also eval and The Land Where PHP Uses eval().

1.2.429.1. Suggestions

  • Use a dynamic feature of PHP to replace the dynamic code

  • Store the code on the disk, and use include

  • Replace create_function() with a closure!

1.2.429.2. Specs

Short name

Structures/EvalUsage

Rulesets

All, Analyze, Appinfo, CE, PHP recommendations, Performances, Security

Exakat since

0.8.4

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Very high

Features

eval

ClearPHP

no-eval

Examples

XOOPS, Mautic

Available in

Entreprise Edition, Community Edition, Exakat Cloud