6

I have developed an API integration, It contains multiple image/file uploads. There are name conflicts if multiple users uploads file with the same name.

I've planned to create dynamic folders with random names to fix this issue (as temp folder & will delete once the process has been done). Are there any methods/techniques available to generate random folders in PHP?

Nikhil
  • 1,450
  • 11
  • 24
  • 1
    I don't think the folder has anything to do with your system crashing the main issue might be with your API implementation of upload – Baba Jan 12 '13 at 05:13
  • Since you asked for "random", I'll also share a function I wrote to create a random directory from [another post](http://stackoverflow.com/a/30010928/145279). – Will May 03 '15 at 07:46

3 Answers3

13

For things like this, I've found the php function uniqid to be useful. Basically, something like this:

$dirname = uniqid();
mkdir($dirname);

And then just move the uploaded file to this directory.

Edit: Forgot to mention, the directory name is not random, but is guaranteed to be unique, which seems to be what you need.

KaeruCT
  • 1,605
  • 14
  • 15
  • Thanks worked perfectly :) don't have much points to make a up ...thanks :) – Nikhil Jan 12 '13 at 05:26
  • 3
    I know this is old, but for anyone looking. `uniqid()` is not guaranteed to be unique, but is likely to be. http://stackoverflow.com/a/4070142/1178671 – Luke Cousins Sep 02 '16 at 20:27
5

I guess that it is best to have a function that tries creating random folders (and verifying if it is successful) until it succeeds.

This one has no race conditions nor is it depending on faith in uniqid() providing a name that has not already been used as a name in the tempdir.

function tempdir() {
    $name = uniqid();
    $dir = sys_get_temp_dir() . '/' . $name;
    if(!file_exists($dir)) {
        if(mkdir($dir) === true) {
            return $dir;
        }
    }
    return tempdir();
}
niekoost
  • 151
  • 2
  • 5
0

Yes its possible using mkdir()Example

<?php
mkdir("/path/to/my/dir", 0700);
?>

For more check this

http://php.net/manual/en/function.mkdir.php

웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91