views:

46

answers:

2

Hello

I am preparing to setup a request routing system in php based on the $_GET array.

For example, for the url ?r=login I'd use include myfiles/".$_GET['r'].".php"; Which would point automatically to myfiles/login.php

I know I need to sanitise the get input, but I'm concerned as it is possible to maliciously redirect the include. Can anyone suggest how to prevent this? Also can I check the file actually exists before calling it?

I have some ideas of my own, I just want to know I've not missed any considerations.

+5  A: 

It is always a good idea not to include files specified through a url. If you still want to do that, use a switch statement or any array to filter the stuff and include only what you need:

Example 1:

$page = $_GET[...];

switch($page){
  case 'login': include 'login_page.php'; break;
  // and so on
  default: die("bye bad guy !");
}

Example 2:

$page = $_GET[...];

$pages = array('page1.php', 'page2.php', 'page3.php');

if( in_array($page, $pages) )
{
    include($page);
{
else
{
   die("bye bad guy !");
} 

I would suggest you to have a look at these related security tuts:

Sarfraz
Is there a better way to setup a routing system in PHP?
YsoL8
@YsoL8: Have a look at example 2 in my answer. That is the one I can think of for the kind of situation you are in.
Sarfraz
@Sarfraz I was hoping to set the path automatically to help keep the structure consistent. You would be against that?
YsoL8
@YsoL8: Nope i am not; the whole idea is that you should do it in such way that if users modify your url from the browser, they should not be able to include any malicious script.
Sarfraz
+1 i agree, this is the way.
Rook
+1  A: 

If you can, use whitelist. If you can't, then:

  • allow underscore and alphanumeric characters only
  • put the include files into a separate directory
Yorirou