tags:

views:

83

answers:

4
+1  Q: 

Include safety

<?php
if (preg_match('/^[a-z0-9]+$/', $_GET['page'])) {
$page = realpath('includes/'.$_GET['page'].'.php');
$tpl = realpath('templates/'.$_GET['page'].'.html');
if ($page && $tpl) {
    include $page;
    include $tpl;
} else {
    // log error!
}
} else {
// log error!
}
?>

How safe would you say this is? Gumbo here on Stack Overflow wrote it.
http://stackoverflow.com/questions/524908/dynamic-include-safety/524959#524959

I wanna hear your opinions.

cheers

A: 

you including your own code. how safe is it?

SilentGhost
+2  A: 

My first thought isn't about safety, but about why in the world would you do that?

Ian P
I used this type of include structure for a project at work. Made adding new pages the boss wanted easier.
epochwolf
pretty sloppy implementation.
Syntax
+2  A: 

I'd say it's pretty safe. Just don't allow anything to write to those folders. PHP files are traditionally inside the web root of a server which is dangerous to start with. It would be better to place the files being loaded to an area that's absolutely inaccessible to the outside given a configuration error or a .htaccess file going missing.

epochwolf
A: 

I could see some potential issues there, especially if the 'page' variable contained '..' or other such things that could allow them to see something they weren't supposed to be able to see.

I do something similar on a few sites of mine, but I would first check 'page' to make sure it references one of a set of allowed pages.

Eric Petroelje
and what's preg_match for?
SilentGhost
What SilentGhost said. the preg_match only matches alphanumeric characters. It would not be possible to add any type of character other than the range specified.
Andy
maybe '..' was a bad example - but there's still lots of things that could go wrong - a symbolic link to another directory, somebody putting something in '/includes' down the road without realizing the consequences, etc.
Eric Petroelje