Primm
Primm

Reputation: 1387

PHP - Make folder in folder

Im pretty sure I simply dont have permission. Thank you for your answers anyway! I will switch to self hosting so I KNOW i have permission!

(I would delete this but it says I cannot b/c there are answers)

Upvotes: 0

Views: 596

Answers (5)

curtisdf
curtisdf

Reputation: 4210

First of all, what is the actual value of $username? Have you verified that it's not empty?

Dealing with the filesystem like this can result in several different problems. I like to put in a lot of extra checks so if something fails I have an easier time knowing why. I also like to deal in absolute directory names where possible, so I don't run into problems with relative paths.

$filesDir = '/path/to/files';
if (!file_exists($filesDir) || !is_dir($filesDir)) {
    throw new Exception("Files directory $filesDir does not exist or is not a directory");

} else if (!is_writable($filesDir)) {
    throw new Exception("Files directory $filesDir is not writable");
}

if (empty($username)) {
    throw new Exception("Username is empty!");
}

$userDir = $filesDir . '/' . $username;

if (file_exists($userDir)) {
    // $userDir should be all ready to go; nothing to do.
    // You could put in checks here to make sure it's 
    // really a directory and it's writable, though.

} else if (!mkdir($userDir)) {
    throw new Exception("Creating user dir $userDir failed for unknown reasons.");
}

mkdir() has some really useful options for setting permissions and making folders multiple levels deep. Check out PHP's mkdir page if you haven't yet.

For security, make sure your exceptions aren't revealing system paths to the end user. You may want to remove the folder paths from your error messages when your code goes onto a public server. Or configure things so your exceptions get logged but not displayed on the web page.

Upvotes: 1

Geoffrey Brier
Geoffrey Brier

Reputation: 799

If you're on Linux or MacOs, there is also another scenario which would consist in calling the mkdir function of your shell.

It'll look like :

system('mkdir -p yourdir/files/$username')

Upvotes: 0

Alex Reynolds
Alex Reynolds

Reputation: 6352

Aren't those the same folder? files/Alex and files/Alex/ are the same. Do you mean files/$username and files/$username/files ? you are doing the same dir twice so that's the error

Upvotes: 0

pckabeer
pckabeer

Reputation: 694

Try this.

mkdir ("./files/$username");

Upvotes: 0

Johndave Decano
Johndave Decano

Reputation: 2113

This is the algorithm for this kind of scenario.

  1. Check if the folder exists.
  2. If the folder exists name the folder to something else or add a random number to it.
  3. Create the new folder.

    http://pastebin.com/VefbrzRS

Upvotes: 0

Related Questions