问题描述:

I have a Json that contains a few contants I'd like to auto-define. It works fine with simple "key": "val" statements, but I can't make it work for eval staments:

$cat test.php

<?php

function objDefinition($obj) {

foreach ($obj as $key => $val) {

$val = $val;

\define($key, $val);

} }

$json = \json_decode(\json_encode([

'COOKIE_EXP' => "eval('time() + (10 * 365 * 24 * 60 * 60)')",

]));

objDefinition($json);

echo COOKIE_EXP;

$php test.php

eval('time() + (10 * 365 * 24 * 60 * 60)')

I know that eval is evil and so on, but this method would save me a lot of code!

Thanks!

网友答案:

I think you should change a bit your data structure and your method, something like this should do the trick:

    function objDefinition($obj) {
        foreach ($obj as $key => $val) {
            if (strstr($val, 'eval=')) {
                \define($key, eval(str_replace('eval=', '', $val)));
            } else {
                \define($key, $val);
            }
        }
    }


    $json = \json_decode(\json_encode([
        'COOKIE_EXP' => "eval=time() + (10 * 365 * 24 * 60 * 60)",
    ]));
网友答案:

@taxicala

You almost got it:

function objDefinition($obj)
{
    foreach ($obj as $key => $val) {
        if (strstr($val, 'eval=')) {
            $val = str_replace('eval=', '', $val);
            eval("\$val = $val;");
        }
        \define($key, $val);
    }
}


$json = \json_decode(\json_encode([
    'COOKIE_EXP' => "eval=time() + (10 * 365 * 24 * 60 * 60)",
]));

\objDefinition($json);
echo COOKIE_EXP;

Thanks!

相关阅读:
Top