1

Not a duplicate of Preventing Directory Traversal in PHP but allowing paths since my problem is in creating a DIR. Named question only works for comparing two already existing files/folders (as made obvious from this question php realpath() returns a blank string).


I have a PHP script that creates a folder based on a users name input.

What is the easiest way to deny the user from creating folders up/back in the structure as he could by typing for example "../../folderName" for the folder name?

I could sanitize the users string and remove slashes and/or dots, but is that a 100% safe way of doing it?

        //compile path to create
        $fPath = $path.$parent.'/'.$name;

        //create the folder
        if (!mkdir($fPath)) {
            //setup response json
            $resp = array();
            $resp['success'] = 0;
            $resp['message'] = "Error: Failed to create folder, check permissions on filesystem.";
        }
        else {

            //setup response json
            $resp = array();
            $resp['success'] = 1;
            $resp['message'] = "Folder successfully created in ".$fPath;

        }

        header('Content-Type: application/json');
        echo json_encode($resp);
Community
  • 1
  • 1
Matt Welander
  • 8,234
  • 24
  • 88
  • 138
  • 1
    this is a very good example to prevent directory traversal http://stackoverflow.com/a/4205278/3859027 – Kevin Apr 02 '15 at 13:46
  • @Ghost Congrats on the 1k php *gold* badge ;-) that'll help speed things up. – Funk Forty Niner Apr 02 '15 at 13:54
  • 1
    @Fred-ii- trusty handy golden hammer :) i've also used that good answer in one of my projects – Kevin Apr 02 '15 at 13:59
  • While the question you mention works well in comparing two existing files/folders, realpath() will not work to compare a basepath to the in-part user-supplied path where he/she wants to create a file/folder. Realpath will return false if supplied with a path to a not-yet existing object. – Matt Welander Apr 02 '15 at 20:23

0 Answers0