MrCarrot
MrCarrot

Reputation: 2758

PHP Including a file based on pathinfo - security concern?

I am redirecting all page requests through a file called index.php which looks at the URL the visitor requested and sees if there is a template file to match.

For example, http://www.website.com/contact will actually route to the index.php script and should check to see if the file /var/html/template/contact.tpl exists and include it if it does.

My concern is with regards to security and null characters, extra dots and slashes, etc. Does any kind of filter need applying to the code below or is the use of pathinfo and the directory prefix enough? Obviously I don't want anyone to be able to maliciously include files outside of the designated template directory.

<?php

define ('TEMPLATES', '/var/html/templates');

$page = pathinfo ($_SERVER['REQUEST_URI'], PATHINFO_FILENAME);

if (file_exists (TEMPLATES . '/' . $page . '.tpl')) {
    include (TEMPLATES . '/' . $page . '.tpl');
} else {
    header ('HTTP/1.0 404 Not Found');
    echo 'Sorry page not found';
}

?>

Upvotes: 0

Views: 705

Answers (1)

calcinai
calcinai

Reputation: 2617

To be 100% safe, make a list of allowed pages and check that it's in that array before returning the page.

You could even try a php glob() e.g..

define ('TEMPLATES', '/var/html/templates/');

$page = TEMPLATES . pathinfo($_SERVER['REQUEST_URI'], PATHINFO_FILENAME) . '.tpl';

if (in_array($page, glob(TEMPLATES . '*.tpl'))) {
    include ($page);
} else {
    header ('HTTP/1.0 404 Not Found');
    echo 'Sorry page not found';
}

This will validate that it's in that folder and that the extension is '.tpl'

Sorry - just edited to make glob() behaviour correct.

Upvotes: 3

Related Questions