Safe dynamic include from $_GET

2019-08-31 03:00发布

问题:

Is this a safe way to include pages from a $_GET parameter:

$pg = basename($_GET['pg']);
if (is_file('views/' . $pg . '.php')) {
  require 'views/' . $pg . '.php';
}

I sanitize the parameter using basename() and all the possible files for including are in a "views/" subdirectory. It seems safe, but I want to be sure.

The reason I want to do this, is because I currently use mod_rewrite to define all my URLs, but I want a single point of entry and I'd rather keep defining them that way than use a router. So I'd have a rule like this:

RewriteRule ^item/(\d+)/?$ index.php?pg=item&id=$1 [L, NC]

And my index.php would look like this:

ob_start();

$pg = basename($_GET['pg']);
if (is_file('views/' . $pg . '.php')) {
  require 'views/' . $pg . '.php';
}

$content = ob_get_clean();

require 'template.php';

Any opinions? Thanks.

回答1:

Wise idea is to write your own array with whitelisted files that can be included. After that, check your $_GET['pg'] against array via in_array()



标签: php security