php 在php中为文件名生成随机字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19083175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:49:02  来源:igfitidea点击:

generate random string in php for file name

phpimagerandomuploadfile-rename

提问by Mike

How would I go about creating a random string of text for use with file names?

我将如何创建用于文件名的随机文本字符串?

I am uploading photos and renaming them upon completion. All photos are going to be stored in one directory so their filenames need to be unique.

我正在上传照片并在完成后重命名它们。所有照片都将存储在一个目录中,因此它们的文件名必须是唯一的。

Is there a standard way of doing this?

有没有标准的方法来做到这一点?

Is there a way to check if the filename already exists before trying to overwrite?

有没有办法在尝试覆盖之前检查文件名是否已经存在?

This is for a single user environment (myself) to show my personal photos on my website however I would like to automate it a little. I don't need to worry about two users trying to upload and generating the same filename at the same time but I do want to check if it exists already.

这是针对单个用户环境(我自己)在我的网站上显示我的个人照片的,但我想稍微自动化一下。我不需要担心两个用户试图同时上传和生成相同的文件名,但我确实想检查它是否已经存在。

I know how to upload the file, and I know how to generate random strings, but I want to know if there is a standard way of doing it.

我知道如何上传文件,我知道如何生成随机字符串,但我想知道是否有标准的方法来做到这一点。

回答by George Brighton

The proper way to do this is to use PHP's tempnam()function. It creates a file in the specified directory with a guaranteedunique name, so you don't have to worry about randomness or overwriting an existing file:

正确的做法是使用 PHP 的tempnam()函数。它创建与指定的目录中的文件保证的唯一的名称,这样你就不必对随机性或覆盖现有文件的担心:

$filename = tempnam('/path/to/storage/directory', '');
unlink($filename);
move_uploaded_file($_FILES['file']['tmp_name'], $filename);

回答by Domecraft

function random_string($length) {
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));

    for ($i = 0; $i < $length; $i++) {
        $key .= $keys[array_rand($keys)];
    }

    return $key;
}

echo random_string(50);

Example output:

示例输出:

zsd16xzv3jsytnp87tk7ygv73k8zmr0ekh6ly7mxaeyeh46oe8

zsd16xzv3jsytnp87tk7ygv73k8zmr0ekh6ly7mxaeyeh46oe8

EDIT

编辑

Make this unique in a directory, changes to function here:

使其在目录中独一无二,在此处更改功能:

function random_filename($length, $directory = '', $extension = '')
{
    // default to this files directory if empty...
    $dir = !empty($directory) && is_dir($directory) ? $directory : dirname(__FILE__);

    do {
        $key = '';
        $keys = array_merge(range(0, 9), range('a', 'z'));

        for ($i = 0; $i < $length; $i++) {
            $key .= $keys[array_rand($keys)];
        }
    } while (file_exists($dir . '/' . $key . (!empty($extension) ? '.' . $extension : '')));

    return $key . (!empty($extension) ? '.' . $extension : '');
}

// Checks in the directory of where this file is located.
echo random_filename(50);

// Checks in a user-supplied directory...
echo random_filename(50, '/ServerRoot/mysite/myfiles');

// Checks in current directory of php file, with zip extension...
echo random_filename(50, '', 'zip');

回答by nurakantech

Hope this is what you are looking for:-

希望这是您正在寻找的:-

<?php
function generateFileName()
{
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789_";
$name = "";
for($i=0; $i<12; $i++)
$name.= $chars[rand(0,strlen($chars))];
return $name;
}
//get a random name of the file here
$fileName = generateName();
//what we need to do is scan the directory for existence of the current filename
$files = scandir(dirname(__FILE__).'/images');//assumed images are stored in images directory of the current directory
$temp = $fileName.'.'.$_FILES['assumed']['type'];//add extension to randomly generated image name
for($i = 0; $i<count($files); $i++)
  if($temp==$files[$i] && !is_dir($files[$i]))
   {
     $fileName .= "_1.".$_FILES['assumed']['type'];
     break;
   }
 unset($temp);
 unset($files);
 //now you can upload an image in the directory with a random unique file name as you required
 move_uploaded_file($_FILES['assumed']['tmp_name'],"images/".$fileName);
 unset($fileName);
?>