Switchfire
Switchfire

Reputation: 556

Include safetly - relative and absolute paths

I wanted to know if it is safe to use includes on pages.

I read using allow_url_include is un-safe, I was using it before with absolute paths, but worked out I could bypass the problem with relative paths, but is this really safe?

Also would something like this really work?

 <?php 
   $header= preg_replace('/[^a-zA-Z0-9_]/', '', $_GET['header']);
   include "http://mysite.co.uk/directory/$header.php"; 
  ?>

Upvotes: 1

Views: 69

Answers (1)

John Conde
John Conde

Reputation: 219824

Here's an example that illustrates the concept I made in the comments above.

$headers = array('loggedin.php','loggedout.php','someotherheader.php', 'etc.php');
$key     = (int) $_GET['header']; // We know it must be a integer so cast to int
$header  = $headers[$key];
include "http://mysite.co.uk/directory/$header"; 

This can be improved upon by verifying the key exists in the array and if it doesn't defaulting to a default header. You also shouldn't be including files via URL. You should be using the path to the file on disk. It's much faster.

Upvotes: 1

Related Questions