O'Reilly logo

Programming PHP, 3rd Edition by Peter MacIntyre, Kevin Tatroe, Rasmus Lerdorf

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

PHP Code

With the eval() function, PHP allows a script to execute arbitrary PHP code. Although it can be useful in a few limited cases, allowing any user-supplied data to go into an eval() call is just begging to be hacked. For instance, the following code is a security nightmare:

<html>
  <head>
    <title>Here are the keys...</title>
  </head>

  <body>
    <?php if ($_REQUEST['code']) {
      echo "Executing code...";

      eval(stripslashes($_REQUEST['code'])); // BAD!
    } ?>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>">
      <input type="text" name="code" />
      <input type="submit" name="Execute Code" />
    </form>
  </body>
</html>

This page takes some arbitrary PHP code from a form and runs it as part of the script. The running code has access to all of the global variables for the script and runs with the same privileges as the script running the code. It’s not hard to see why this is a problem—type this into the form:

include("/etc/passwd");

Never do this. There is no practical way to ensure such a script can ever be secure.

You can globally disable particular function calls by listing them, separated by commas, in the disable_functions configuration option in php.ini. For example, you may never have need for the system() function, so you can disable it entirely with:

disable_functions = system

This doesn’t make eval() any safer, though, as there’s no way to prevent important variables from being changed or built-in constructs such as echo() being called.

Note that the preg_replace() function with the /e option ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required