eval
eval(string $code): mixed
A language construct that executes a string as PHP code: literal-expression evaluation is deterministic; feeding user input into eval is arbitrary code execution — the core risk lesson of this entry.
C C23
#include <ctype.h>
#include <stdio.h>
// C has no eval: a tiny recursive-descent parser is the controlled-evaluation demo
static const char *p;
static long term(void); // forward declaration
static long term_operand(void) {
long n = 0;
while (isdigit((unsigned char)*p)) { n = n * 10 + (*p - '0'); p++; }
return n;
}
static long term(void) {
long n = term_operand();
while (*p == '*' || *p == '/') {
char op = *p++;
long m = term_operand();
n = (op == '*') ? n * m : n / m;
}
return n;
}
static long expr(void) {
long n = term();
while (*p == '+' || *p == '-') {
char op = *p++;
long m = term();
n = (op == '+') ? n + m : n - m;
}
return n;
}
int main(void) {
p = "2+3*4";
printf("%ld\n", expr()); // 14: * binds tighter than +
p = "10-2*3";
printf("%ld\n", expr()); // 4
return 0;
}
14 4
C++ C++26
#include <cctype>
#include <iostream>
// C++ has no eval either: same tiny recursive-descent parser as C
struct Parser {
const char *p;
long operand() {
long n = 0;
while (std::isdigit(static_cast<unsigned char>(*p))) { n = n * 10 + (*p - '0'); p++; }
return n;
}
long term() {
long n = operand();
while (*p == '*' || *p == '/') {
char op = *p++;
long m = operand();
n = (op == '*') ? n * m : n / m;
}
return n;
}
long expr() {
long n = term();
while (*p == '+' || *p == '-') {
char op = *p++;
long m = term();
n = (op == '+') ? n + m : n - m;
}
return n;
}
};
int main() {
Parser a{"2+3*4"};
std::cout << a.expr() << "\n"; // 14: * binds tighter than +
Parser b{"10-2*3"};
std::cout << b.expr() << "\n"; // 4
return 0;
}
14 4
C# v11.0.100
// C# has no direct eval: a tiny recursive-descent parser is the controlled-evaluation demo
long Eval(string s) {
var p = new Parser { S = s };
return p.Expr();
}
Console.WriteLine(Eval("2+3*4")); // 14: * binds tighter than +
Console.WriteLine(Eval("10-2*3")); // 4
class Parser {
public string S = "";
public int I;
long Operand() {
long n = 0;
while (I < S.Length && char.IsDigit(S[I])) { n = n * 10 + (S[I] - '0'); I++; }
return n;
}
public long Term() {
long n = Operand();
while (I < S.Length && (S[I] == '*' || S[I] == '/')) {
char op = S[I++];
long m = Operand();
n = op == '*' ? n * m : n / m;
}
return n;
}
public long Expr() {
long n = Term();
while (I < S.Length && (S[I] == '+' || S[I] == '-')) {
char op = S[I++];
long m = Term();
n = op == '+' ? n + m : n - m;
}
return n;
}
}
14 4
Go v1.27.4
package main
import "fmt"
// Go has no eval: a tiny recursive-descent parser is the controlled-evaluation demo
type parser struct {
s string
i int
}
func (p *parser) operand() int {
n := 0
for p.i < len(p.s) && p.s[p.i] >= '0' && p.s[p.i] <= '9' {
n = n*10 + int(p.s[p.i]-'0')
p.i++
}
return n
}
func (p *parser) term() int {
n := p.operand()
for p.i < len(p.s) && (p.s[p.i] == '*' || p.s[p.i] == '/') {
op := p.s[p.i]
p.i++
m := p.operand()
if op == '*' {
n *= m
} else {
n /= m
}
}
return n
}
func (p *parser) expr() int {
n := p.term()
for p.i < len(p.s) && (p.s[p.i] == '+' || p.s[p.i] == '-') {
op := p.s[p.i]
p.i++
m := p.term()
if op == '+' {
n += m
} else {
n -= m
}
}
return n
}
func eval(s string) int { return (&parser{s: s}).expr() }
func main() {
fmt.Println(eval("2+3*4")) // 14: * binds tighter than +
fmt.Println(eval("10-2*3")) // 4
}
14 4
Java v27.0.1
// Java has no eval since Nashorn was removed (JDK 15):
// a tiny recursive-descent parser is the controlled-evaluation demo
class Parser {
String s;
int i = 0;
Parser(String s) { this.s = s; }
long operand() {
long n = 0;
while (i < s.length() && Character.isDigit(s.charAt(i))) { n = n * 10 + (s.charAt(i) - '0'); i++; }
return n;
}
long term() {
long n = operand();
while (i < s.length() && (s.charAt(i) == '*' || s.charAt(i) == '/')) {
char op = s.charAt(i++);
long m = operand();
n = (op == '*') ? n * m : n / m;
}
return n;
}
long expr() {
long n = term();
while (i < s.length() && (s.charAt(i) == '+' || s.charAt(i) == '-')) {
char op = s.charAt(i++);
long m = term();
n = (op == '+') ? n + m : n - m;
}
return n;
}
}
public class Main {
static long eval(String s) { return new Parser(s).expr(); }
public static void main(String[] args) {
System.out.println(eval("2+3*4")); // 14: * binds tighter than +
System.out.println(eval("10-2*3")); // 4
}
}
14 4
JavaScript v26.13.1
// eval() executes a string in the current scope; strict mode bans it entirely.
// The example uses a FIXED LITERAL — never feed user input into eval().
console.log(eval("2 + 3 * 4"));
14
PHP v8.6.0
$result = eval('return 2 + 3 * 4;'); // a language construct: no <?php tags inside
echo $result, "\n"; // 14 — identical to writing the expression inline
// DANGER: never concatenate user input into eval() — that is arbitrary code execution
14
Python v3.15.2
import ast
# eval() evaluates an EXPRESSION; exec() runs statements.
# The example uses a FIXED LITERAL — never feed user input into eval().
print(eval("2 + 3 * 4"))
# safe alternative: literal_eval accepts literals only (no calls, no names)
print(ast.literal_eval("[1, 2, 3]"))
14 [1, 2, 3]
Rust v1.99.1
// Rust has no eval: a tiny recursive-descent parser is the controlled-evaluation demo
struct Parser<'a> {
s: &'a [u8],
i: usize,
}
impl<'a> Parser<'a> {
fn operand(&mut self) -> i64 {
let mut n = 0i64;
while self.i < self.s.len() && self.s[self.i].is_ascii_digit() {
n = n * 10 + (self.s[self.i] - b'0') as i64;
self.i += 1;
}
n
}
fn term(&mut self) -> i64 {
let mut n = self.operand();
while self.i < self.s.len() && (self.s[self.i] == b'*' || self.s[self.i] == b'/') {
let op = self.s[self.i];
self.i += 1;
let m = self.operand();
n = if op == b'*' { n * m } else { n / m };
}
n
}
fn expr(&mut self) -> i64 {
let mut n = self.term();
while self.i < self.s.len() && (self.s[self.i] == b'+' || self.s[self.i] == b'-') {
let op = self.s[self.i];
self.i += 1;
let m = self.term();
n = if op == b'+' { n + m } else { n - m };
}
n
}
}
fn eval(s: &str) -> i64 {
let mut p = Parser { s: s.as_bytes(), i: 0 };
p.expr()
}
fn main() {
println!("{}", eval("2+3*4")); // 14: * binds tighter than +
println!("{}", eval("10-2*3")); // 4
}
14 4
TypeScript v26.13.1
// eval() exists but is banned under strict mode and ESLint's no-eval rule.
// The example uses a FIXED LITERAL — never feed user input into eval().
console.log(eval("2 + 3 * 4"));
14
Language differences
PHP: eval is a language construct (NOT a function — no variable-function calls, no named arguments); the string must NOT carry <?php tags; the code runs in the calling scope and return can hand a value back; parse errors throw ParseError (PHP 7+).
Core danger: concatenating user input into an eval string IS arbitrary code execution — the manual says "very dangerous"; the example uses a fixed literal only, and real code must whitelist-validate first.
Python: eval evaluates an expression, exec runs statements; ast.literal_eval accepts literals only (numbers/strings/lists/dicts) — a safe alternative that executes no arbitrary code.
JavaScript/TypeScript: eval exists but is banned in strict mode and blocked by ESLint's no-eval by default; indirect eval (0, eval)(...) runs in the global scope — avoid it when you can.
Java: the Nashorn ScriptEngine was removed in JDK 15, so standard Java has no eval; the example hand-writes a recursive-descent parser (+ - * /, multiplication first) as a "controlled evaluation" demo.
C#: no direct eval (CSharpCodeProvider compiles whole assemblies — too heavy to count); Go/Rust/C/C++ are compiled languages without runtime evaluation — the same hand-written parser demonstrates controlled evaluation.
Hand-written parser lesson: under a restricted grammar (expr := term ((‘+’|‘-’) term)*, term := num ((‘*’|‘/’) num)*) the values 2+3*4=14 and 10-2*3=4 are deterministic — restricting expressive power IS the essence of protection.
PHP alternatives: prefer match/callback tables/config arrays for expression needs; use a templating engine sandbox for template needs, not eval.