简体   繁体   中英

Create Random Folders - PHP

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?

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.

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();
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM