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
Release: 2024-12-08 16:36:11
Original
545 people have browsed it

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;
}
Copy after login
function calculator2($str){
    $fn = create_function("", "return ({$str});" );
    return $fn();
};
Copy after login

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);
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template