directory – php: path in querystring – best way to prevent hacks and bugs? – Education Career Blog

hey guys,
i know it’s not the best way of doing this but the whole thing is just a little project which doesn’t need anything more difficult.

i’m passing directory names along with my url like

i’m looking for the best way to check if the dir exists and i want to (at least) kind of prevent people from going up in hierarchy.

now what i’m doing right now (almost) works, however i think there’s a much better and easier and shorter way for that:

    if(isset($_GET'p')) {
    if (realpath($_GET'p')) {
        if (substr(PATH, 0, 1) == "" || substr(PATH, 0, 1) == "/" || substr(PATH, 0, 2) == "./" || substr(PATH, 0, 3) == "../") {
            print "directory is forbidden!";
        } else {
            define(PATH, $_GET'p'); 
    } else {
        print "directory does not exist!";
} else { define(PATH, "root"); } 

what would you do?


You should be mapping user input to a predetermined list of valid file names rather than allowing arbitrary paths to be used.

Having said that, if you’re just experimenting on a personal development machine, you can prepend any user submitted path with a path to an allowed base directory to help prevent system traversal. In addition, disallow any submitted paths that contain ./, ../ or ~/(not just at the beginning of the string, but anywhere).

You can use preg_match for this.

if (preg_match('#(\./|\.\./|~/|\\\)#', $_GET'p')) {
    // disallow

Again, this is just for experimental development purposes. With any code intended for real use, you should map input to a predetermined list of valid paths.

Also, the logic of your code is flawed. PATH is never set before its first use, and even if you do set it realpath is used which escapes the traveral characters rendering the substr checks ineffective, and you’re using a define where a variable is much more appropriate.

Leave a Comment