Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: prevent folder hacking - if path has ../ in it?

Tags:

path

php

i'm doing a simple thingy in php and i wonder how i can test if the variable $path contains the following structure ../

so i'll simply have a ?path=somepath structure in my url, and if anybody would enter ../ it allows him to go one directory up. I know of course that that's not the best solution, however for my little thingy it's enough if i just test the $path variable for a string of "../" in it. if so die();

i'm not sure what's the best way to test that!

regards matt

like image 212
matt Avatar asked Jul 27 '10 09:07

matt


2 Answers

Instead of doing that, you could just call realpath() on it and check if the path it's supposed to be in is a prefix of that.

Even better, why not keep a whitelist and reject anything not in it?

like image 104
Daniel Egeberg Avatar answered Sep 20 '22 13:09

Daniel Egeberg


to answer your question:

if(strpos($path,'../') !== false){
  // looks like someone 's trying to hack here - simply
  // do nothing (or send an email-notification to yourself
  // to be informed and see how often this happens)
}else{
  // here comes the magic

}

but: you really shouldn't do so. if you want an easy solution, use a switch-statement for every possible $path and include the relevant file (or whatever you have to do).

like image 21
oezi Avatar answered Sep 20 '22 13:09

oezi