PDA

View Full Version : A secure PHP include?


Cassius
01-16-2005, 07:19 AM
I'm using the PHP "include" function for including the header and footer on a page. I want to make sure that the right page is included and that the website stays secure. I'm considering a simple solution to make sure that it works.


<?php
$this1 = "my";
$this2 = "in";
$this3 = "clude";
$exten_a7f = ".txt";
$path_gr4 = "../something/";

if ( $path_gr4 . $this1 . #this2 . $this3 . $exten_a7f == "../something/myinclude.txt");
{
include($path_gr4 . $this1 . #this2 . $this3 . $exten_a7f);
}
else {

echo "All your bases";
}
?>


Does this seem like an absurd approach that's still insecure? Do any of you know a better way to do this?

I'm considering using the "preg_match" function with Regular Expressions for validation, but I'm new to using Regular Expressions (I only understand the simple stuff) and I'm not sure about how to approach implementation. Like, should I be checking for special characters that shouldn't be there or only the characters that should be there? This is why I've leaned toward the aforementioned solution, since I don't want to screw things up. That goes both ways since the aforementioned was kind of stupid and already screwed up.

Thysis
01-16-2005, 08:53 AM
I'm not understanding why you don't just do something like
include(../something/my_include.txt);
or
require(../something/my_include.txt);

I mean, if it's your code and your not using GETs or something to define your includes, I don't understand why you wouldn't just use 'include' or 'require'. If your internal code is already compromised, no point seeing if you included the right file since your already screwed...

If it's provided by user vars, you could using something like this..
<?php
// Setup vars
$FileExt = ".php";
$IncPath = "./content/";
$NotFound = "file_not_found";
$Default = "home";

// If ?p= doesn't exist set it to Default
if(empty($_GET['p'])) { $p = $Default; }
else { $p = $_GET['p']; }

// Make sure there is nothing but letters in ?p=
if (!ereg("^[a-z]+$",$p)) {
die("Try hacking somebody else's site."); }

// Finally include the file if it exists locally
if(file_exists($IncPath.$p.$FileExt)) {
include($IncPath.$p.$FileExt);
} else {
include($IncPath.$NotFound.$FileExt); die(); }
?>
It works pretty well, if your even more paranoid, you could put stuff to check the referrer and whatnot.

If you haven't done so already, make sure "register_globals = Off" is already set in your php.ini file so people can't just put "?this1=www.badwebsite.com". That way you just have to worry about the vars your manually grab with $_GET and etc.

Cassius
01-16-2005, 11:19 PM
Thank you for your help, I understand now.