Andreas
Andreas

Reputation: 555

PHP eval does not produce expected results

Despite the fact that it is recommended to do not use eval(), I have to use it for a certain part of my project.

In general I want to provide a system administrator a way to upload files containing php code – the php code is stored in a database and eventually loaded and executed when certain criteria are met.

As this is a intra net application only accessible by a few people the security aspect is not serious.

The php code executed by eval() could be any code possible.

$some_array = array();

$some_array[0] = 'Hello World';

echo $some_array[0];

The output of this code is simply Hello World.

eval("

$some_array = array();

$some_array[0] = 'Hello World';

echo $some_array[0];

");

Theoretically the output of this code should be the same, but actually it is not.

I am getting this error messages:

Notice: Undefined variable: some_array in C:\xampp\htdocs\test.php on line 8

Notice: Undefined variable: some_array in C:\xampp\htdocs\test.php on line 8

Notice: Undefined variable: some_array in C:\xampp\htdocs\test.php on line 10

Parse error: syntax error, unexpected '=' in C:\xampp\htdocs\test.php(12) : eval()'d code on line 3

It seems like a simple thing – however this problem is already making me busy for several hours…

Upvotes: 0

Views: 49

Answers (1)

DaKirsche
DaKirsche

Reputation: 352

You have to use single quotes like:

eval('

$some_array = array();

$some_array[0] = \'Hello World\';

echo $some_array[0];

');

Otherwise PHP will try to replace the $some_array in your string with the known value which does not exist.

Upvotes: 2

Related Questions