Jump to content

directory traversal prevention


cssfreakie

Recommended Posts

Hi all,

 

last few days i searched my butt of on articles about this topic but most don't seem to provide a solution, more a general idea of what it is. So i thought i mix up some functions and asks you guys to see if this could be a working example to prevent directory traversal and the prevention of including remote files. So the files should be on my server.

 

What i try to do is to retrieve a $_GET['variable'] which stands for a filename and afterwards include this file name if the file exists. Any tips and tricks are welcome.

if (file_exists(basename(realpath($_GET['filenamehere'])))){
    echo 'file exists';
}else{
    echo 'file doesn\'t exist';
}

 

thanks in advance!

Link to comment
https://forums.phpfreaks.com/topic/228919-directory-traversal-prevention/
Share on other sites

http://www.phpfreaks.com/tutorial/php-security

 

Section 9 is about directory traversal but you should also pay attention to Section 6 as it is somewhat related (I would suggest reading the whole tutorial though, as the whole thing has good info about security)

 

 

Thanks Crayon! I googled my butt off but did't end up at the security manual at php freaks. Ill sure have a look at it since security is my top priority :D

 

I changed the code a bit though and i think this works pretty good. Anyone want to Break/critique it?  ;D

 

$file = basename('testpage.php'); // this seems to strip of pretty much anything so this would be the Get variable

$path = 'pages/'; // a path to a folder that should be the only that it should have access to (besides .htaccs stuff)
if (file_exists(realpath($path.$file))){
    echo 'file exists'.realpath($path.$file);
    include (realpath($path.$file));
}else{
    echo 'file doesn\'t exist';
}

 

Edit, that second soultion in  the manual seems to be my favorite since it's more dynamic. But i really wonder if the above isn't good too, without the power of regex.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.