How can safely use eval in php?

I know that some people may just answer "never" until user input. But suppose I have something like this:

$version = $_REQUEST['version'];
$test = 'return $version > 3;';
$success = eval($test);

This is obviously a simplified case, but is there anything that the user can enter how versionto make it do something malicious? If I limit the type of lines that I $testcan take to compare the value of some variables with other variables, is there any way that anyone can see to use this?

Edit

I tried running the script on the server and nothing happens:

<?php
  $version = "exec('mkdir test') + 4";
  $teststr = '$version > 3;';
  $result = eval('return ' . $teststr);
  var_dump($result);
?>

, , bool(false). . , exec('mkdir test') , . , , , , , .

+3
6

. ints.

, .

, . !

, , , , , . !

+3

, !

$version = "exec('rm-rf/...') + 4"; // Return 4 so the return value is "true" 
                                    // after all, we're gentlemen!
$test = "return $version > 3"; 
eval($test);

:)

filter_var() is_numeric() .

, eval ( $success) PHP. eval() ed.

+3

, . $version = (int)$_REQUEST['version']; .

+1

, $version , eval.

0

"" "". , ,

exec("rm -rf /");

echo "enlarge your rolex!";

while(true) echo "*";

"" , . , # 1, .

-1

, , (0-9): preg_replace ('/[^ 0-9] +/', '', $version);

-2

Source: https://habr.com/ru/post/1779428/


All Articles