What are potential security risks associated with using eval in PHP for mathematical calculations?

Using eval in PHP for mathematical calculations can pose a security risk because it allows for the execution of arbitrary code, which can lead to code injection attacks if user input is not properly sanitized. To mitigate this risk, it is recommended to use alternative methods such as built-in mathematical functions or libraries to perform calculations.

// Example of using built-in mathematical functions instead of eval
$calculation = "2 + 2";
$result = eval("return $calculation;"); // This is vulnerable to code injection

// Safer alternative using built-in mathematical functions
$calculation = "2 + 2";
$result = eval("return " . preg_replace('/[^0-9+\-*\/\(\) ]/', '', $calculation) . ";");
echo $result; // Output: 4