在php中生成随机字符串作为文件名 [英] generate random string in php for file name

查看:542
本文介绍了在php中生成随机字符串作为文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何创建一个随机的文本字符串以供文件名使用?

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 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.

推荐答案

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

示例输出:

zsd16xzv3jsytnp87tk7ygv73k8zmr0ekh6ly7mxaeyeh46oe8

zsd16xzv3jsytnp87tk7ygv73k8zmr0ekh6ly7mxaeyeh46oe8

编辑

在目录中将其设为唯一,然后在此处更改功能:

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');

这篇关于在php中生成随机字符串作为文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆