9

ファイル名で使用するランダムなテキスト文字列を作成するにはどうすればよいですか?

写真をアップロードし、完了時に名前を変更しています。すべての写真は 1 つのディレクトリに保存されるため、ファイル名は一意である必要があります。

これを行う標準的な方法はありますか?

上書きする前にファイル名が既に存在するかどうかを確認する方法はありますか?

これは、個人の写真を自分のウェブサイトに表示するための単一ユーザー環境 (自分自身) 用ですが、少し自動化したいと考えています。2 人のユーザーが同時に同じファイル名をアップロードして生成しようとすることを心配する必要はありませんが、既に存在するかどうかを確認したいと考えています。

ファイルをアップロードする方法と、ランダムな文字列を生成する方法は知っていますが、それを行う標準的な方法があるかどうかを知りたいです。

4

3 に答える 3

30
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

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');
于 2013-09-29T21:01:08.300 に答える
1

これがあなたが探しているものであることを願っています:-

<?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);
?>
于 2013-09-29T21:28:36.830 に答える