php随机图像文件名

bus*_*man 7 php

好吧,我使用谷歌上发现的一个片段来获取用户上传的图像并将其放在我的目录下的内容下

但我担心重复,所以我要把它上传为一个随机数

好吧,这里是我的代码,你可以理解,无论如何我想通过它

<label for="file">Profile Pic:</label> <input type="file" name="ProfilePic" id="ProfilePic" /><br />

<input type="submit" name="submit" value="Submit" />

$ProfilePicName = $_FILES["ProfilePic"]["name"];
$ProfilePicType = $_FILES["ProfilePic"]["type"];
$ProfilePicSize = $_FILES["ProfilePic"]["size"];
$ProfilePicTemp = $_FILES["ProfilePic"]["tmp_name"];
$ProfilePicError = $_FILES["ProfilePic"]["error"];

$RandomAccountNumber = mt_rand(1, 99999);  
echo $RandomAccountNumber; 
move_uploaded_file($ProfilePicTemp, "Content/".$RandomAccountNumber.$ProfilePicType);
Run Code Online (Sandbox Code Playgroud)

然后基本上所有这一切我试着让它把随机数放在我的数据库中

有人给了我一个新的片段,看起来它会做我想要的但现在文件不是一直到我的目录

$RandomAccountNumber = uniqid();
echo $RandomAccountNumber;

move_uploaded_file($ProfilePicName,"Content/".$RandomAccountNumber);
Run Code Online (Sandbox Code Playgroud)

Div*_*com 17

尝试使用php uniqid方法生成您需要的唯一ID

http://php.net/manual/en/function.uniqid.php

$RandomAccountNumber = uniqid();
move_uploaded_file($ProfilePicTemp, "Content/" . $RandomAccountNumber);
Run Code Online (Sandbox Code Playgroud)


Mad*_*iha 5

当我上传图像时,我通常将其保存为sha1()图像内容(sha1_file()).这样,你就得到了一石二鸟:你永远不会(如果你这样做,去填写最近的彩票)获得重复的文件名,并且,你将防止重复的图像(因为重复的图像将具有相同的校验和) .

然后,您有一个数据库来整理哪个图像,并将其正确显示给用户.

  • 我认为这种方法会很糟糕.如果两个用户上传相同的LOL cat然后删除它,该怎么办? (2认同)

小智 5

这是我上传图片时使用的:session_id()time()和随机字符串的组合:

$rand = genRandomString();
$final_filename = $rand."_".session_id()."_".time();

function genRandomString() 
{
    $length = 5;
    $characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWZYZ";

    $real_string_length = strlen($characters) ;     
    $string="id";

    for ($p = 0; $p < $length; $p++) 
    {
        $string .= $characters[mt_rand(0, $real_string_length-1)];
    }

    return strtolower($string);
}
Run Code Online (Sandbox Code Playgroud)

我希望这会有所帮助。