Best way to avoid code injection in PHP

pek picture pek · Sep 2, 2008 · Viewed 25.1k times · Source

My website was recently attacked by, what seemed to me as, an innocent code:

<?php
  if ( isset( $ _GET['page'] ) ) {
    include( $ _GET['page'] . ".php" );
  } else {
    include("home.php");
  }
?>

There where no SQL calls, so I wasn't afraid for SQL Injection. But, apparently, SQL isn't the only kind of injection.

This website has an explanation and a few examples of avoiding code injection: http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html

How would you protect this code from code injection?

Answer

Jeremy Ruten picture Jeremy Ruten · Sep 2, 2008

Use a whitelist and make sure the page is in the whitelist:

  $whitelist = array('home', 'page');

  if (in_array($_GET['page'], $whitelist)) {
        include($_GET['page'].'.php');
  } else {
        include('home.php');
  }