Home >Backend Development >PHP Tutorial >How Can I Safely Evaluate Mathematical Formulas Passed as Strings in PHP?

How Can I Safely Evaluate Mathematical Formulas Passed as Strings in PHP?

DDD
DDDOriginal
2024-12-08 16:36:11493browse

How Can I Safely Evaluate Mathematical Formulas Passed as Strings in PHP?

How to evaluate formula passed as string in PHP?

Problem:

I'm trying to figure out the proper and safer way to execute mathematical operation passed as string. In my scenario it is values fetched from image EXIF data.

After little research I found two way of doing it.

function calculator1($str){
    eval("$str = $str;");
    return $str;
}
function calculator2($str){
    $fn = create_function("", "return ({$str});" );
    return $fn();
};

Both examples require string cleanup to avoid malicious code execution. Is there any other or shorter way of doing so?

Answer:

function calculator3($str){
    $m = new EvalMath;
    return $m->evaluate($str);
}

This method uses the EvalMath class, which is specifically designed to safely evaluate mathematical expressions from untrusted sources. It provides robust error checking and only evaluates a limited set of functions.

Here's an example of how to use it:

$str = '2+2';
$result = calculator3($str);
echo $result; // Output: 4

The above is the detailed content of How Can I Safely Evaluate Mathematical Formulas Passed as Strings in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn