Eval () PHP Construct

Eval() stores code in a database for later execution

The PHP eval () construct is used to evaluate an input string as PHP and then process it as such. Eval() is not a function, but it works like one in the sense that it outputs everything—except instead of outputting it as text, it outputs it as PHP code to be executed. One use of the eval() construct is to store code in a database to execute later.

Example of Eval() Language Construct

Here is a simple example of coding for the eval() language construct.

 "; 
 eval("\$a = \"$a\";"); 
 print $a . "
"; 
 ?> 

This code example outputs My friends are $name and $name2 when first called with the print statement, and it outputs My friends are Joe and Jim when called the second time after running eval ().

Requirements and Characteristics of Eval()

  • The passed code can't be wrapped in opening and closing PHP tags.
  • The passed code must be valid PHP.
  • All statements must be terminated with a semicolon.
  • A return statement terminates the code evaluation.
  • Any variable defined or changed in eval() remains after it terminates.
  • What a fatal error occurs in the evaluated code, the script exits.
  • Because eval() is a language construct and not a function, it can't be used in higher-order functions.

Danger of Using Eval()

The PHP manual discourages the use of the eval() construct, stressing its use is "very dangerous" because arbitrary PHP code can be executed. Users are instructed to use any other option than eval() unless that is not possible.

The use of PHP eval() construct presents security risks.

Format
mla apa chicago
Your Citation
Bradley, Angela. "Eval () PHP Construct." ThoughtCo, Aug. 21, 2017, thoughtco.com/eval-php-function-2694048. Bradley, Angela. (2017, August 21). Eval () PHP Construct. Retrieved from https://www.thoughtco.com/eval-php-function-2694048 Bradley, Angela. "Eval () PHP Construct." ThoughtCo. https://www.thoughtco.com/eval-php-function-2694048 (accessed November 20, 2017).