If you have ever tried to access PHP from a database and run it from within your website you will note that it outputs as text, and the server will not parse that PHP code. Following is a great quick-fix that will enable you to store and ‘execute’ PHP code stored from within a database using the PHP eval() function.
About
eval() will evaluate a string as PHP code. A return() statement will terminate the evaluation of the string immediately. eval() most often used to execute PHP code that’s built at runtime or to get around some of the limitations in the PHP parser. Use of eval() can often be a little tricky, and I’ve heard more than one programmer say that evil() would be a more appropriate name for the function.
Example
<?php
$name = 'Dom';
$name2 = 'Joe';
$a = 'My friends are $name and $name2';
print $a . "<br>";
eval("\$a = \"$a\";");
print $a . "<br>";
?>
Output
My friends are $name and $name2
My friends are Dom and Joe
This above code would output ‘My friends are $name and $name2′ when first called with the print statement, but would output ‘My friends are Dom and Joe’ when called the second time after running eval().
Using eval on code from database
This is the code I utilise to extract a block of text containing PHP code from a database that needs to be executed. When used, your database field may contain a mix of normal text, html, and PHP code within normal PHP tags.
$content = eval('?>' . $content . '<?php ');
Simple!
Vulnerabilities
An eval() attack may occur when user inputs are not validated correctly, meaning that a remote user can supply nasty manipulative code (or a user may inadvertently submit hazardous code) in a URL or via a form that will pass arbitrary code to an eval() statement which will result in code execution. To remedy this, always validate user data. You can read more on the eval() injection here.
If you liked this article, you may also like:
Recent Comments