Random name php

Hi

What is the best way to create a random name for a folder?

It will be used for the name of the folder for storing documents. But a lot of folders will be created, so it needs to be unique every time it was possible.

The length should be about 7 characters.

+3
source share
9 answers

If it should be unique, I would forget that it is random and just increments the counter. If you need to associate the contents of folders with entries in the database, all the better. You can simply have an auto-increment column in your database and use it as part of the folder name.

+5
source

PHP uniqid(), more_entropy true.

sha1( microtime() )

+11

, :

function makeRandomString($max=6) {
    $i = 0; //Reset the counter.
    $possible_keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $keys_length = strlen($possible_keys);
    $str = ""; //Let declare the string, to add later.
    while($i<$max) {
        $rand = mt_rand(1,$keys_length-1);
        $str.= $possible_keys[$rand];
        $i++;
    }
    return $str;
}

EDIT: , - . , , .

+3

7 char ( )?

YYYYmmDDHHMMSS ( , , ).

  • YYYY =
  • mm =
  • DD =
  • HH = (24 )
  • MM =
  • SS =

, , , .

PHP:

<?php
$dirName = date( 'YmdHis', time() );
@mkdir( $dirName )
?>
+2

?

, , 36 (26 + 10 ). , .

+1

php , tmpnam, ; ( , :)

+1

, 7 , , , , 36 (0-9 az), , , , .

0

"rh". mt_rand (10000,99999)

Then check if it is unique and regenerates if it is not. In some ways, this is better than maintaining the state as a counter, because less can go wrong.

do {
  $f = "rh" . mt_rand(10000,99999);
} while (file_exists($f));
0
source

I think the best approach to naming is to use the uniqid () function.

$folder_name = uniqid();// eg: 4b3403665fea6

or with a static prefix:

$folder_name = uniqid('folder_'));// eg: folder_537834f6e981a

or with the prefix of today (date):

$folder_name = uniqid(date('h-i-s')._); //eg: 04-23-59_537835dff2017
0
source

Source: https://habr.com/ru/post/1718731/


All Articles