note 107377 added to function.eval

From: Date: Sat, 04 Feb 2012 22:51:11 +0000
Subject: note 107377 added to function.eval
Groups: php.notes 
Request: Send a blank email to php-notes+get-185856@lists.php.net to get a copy of this message
If you want to allow math input and make sure that the input is proper mathematics and not some hacking code, you can try this: <?php $test = '2+3*pi'; // Remove whitespaces $test = preg_replace('/\s+/', '', $test); $number = '(?:\d+(?:[,.]\d+)?|pi|π)'; // What is a number $functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)'; // Allowed PHP functions $operators = '[+\/*\^%-]'; // Allowed math operators $regexp = '/^(('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?2))?)+$/'; // Final regexp, heavily using recursive patterns if (preg_match($regexp, $q)) { $test = preg_replace('!pi|π!', 'pi()', $test); // Replace pi with pi function eval('$result = '.$test.';'); } else { $result = false; } ?> I can't guarantee you absolutely that this will block every possible malicious code nor that it will block malformed code, but that's better than the matheval function below which will allow malformed code like '2+2+' which will throw an error. ---- Server IP: 89.31.146.176 Probable Submitter: 109.190.6.11 ---- Manual Page -- http://www.php.net/manual/en/function.eval.php Edit -- https://master.php.net/note/edit/107377 Del: integrated -- https://master.php.net/note/delete/107377/integrated Del: useless -- https://master.php.net/note/delete/107377/useless Del: bad code -- https://master.php.net/note/delete/107377/bad+code Del: spam -- https://master.php.net/note/delete/107377/spam Del: non-english -- https://master.php.net/note/delete/107377/non-english Del: in docs -- https://master.php.net/note/delete/107377/in+docs Del: other reasons-- https://master.php.net/note/delete/107377 Reject -- https://master.php.net/note/reject/107377 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#185856) next »