Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save junaidtk/e9a9f6ff4b1735328aea953bd2a91ebf to your computer and use it in GitHub Desktop.
Save junaidtk/e9a9f6ff4b1735328aea953bd2a91ebf to your computer and use it in GitHub Desktop.
Eval() in PHP and Javascript
The eval is used to execute the a string value. If you want to execute a string value like
an arithmetic string eg: "4+3*6", then you can use the eval function to calculate the string.
In php and javascript you can use the eval() function.
Javascript:
===========
The eval() function will leads to many syntax error whenever the statement inside the function is not executable.
So you can use the try{}catch{} method.
var statement = "4+3*6";
try{
var calculated = eval(statement);
}catch(e){
}
PHP
=====
PHP will also produce parse error while running the eval. In php 7 it will thrown an exeption.
So we can use the try{}catch{} method to catch the exception and it wont halt the execution.
But in php below 7 it will create parse error which will stop the php execution.
So before php 7 you can use any other method to solve the parse error. Please refer.
https://stackoverflow.com/questions/3223899/php-eval-and-capturing-errors-as-much-as-possible
You can write a function to check a ,valid eval statement. like below.
function is_valid_eval_code($code){
return @eval($code . "; return true;");
}
This will return true if eval code is valid one.
eg:
$code = "4*3*6-4";
if(phpversion() >= 7){
try {
$value = eval("return $code;");
} catch (ParseError $e) {
echo $e->getMessage();
}
}else{
$value = eval("return $code;")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment