如何重命名图像或添加随机数的图像,使唯一的名称


How to rename image or add random number to the image to make unique name

$target = "upload/";
$targetx = $target . basename( $_FILES['photo']['name']);
if(move_uploaded_file($_FILES['photo']['tmp_name'], $targetx))
{
}
else {
}
$targetx = $target . basename( $_FILES['photo2']['name']);
if(move_uploaded_file($_FILES['photo2']['tmp_name'], $targetx))
{
}
else {
}
$targetx = $target . basename( $_FILES['photo3']['name']);
if(move_uploaded_file($_FILES['photo3']['tmp_name'], $targetx))
{
}
else {
}
$targetx = $target . basename( $_FILES['photo4']['name']);
if(move_uploaded_file($_FILES['photo4']['tmp_name'], $targetx))
{
}
else {
echo "Sorry, there was a problem uploading your file.";
}
$photo=($_FILES['photo']['name']);
$photo2=($_FILES['photo2']['name']);
$photo3=($_FILES['photo3']['name']);
$photo4=($_FILES['photo4']['name']);

每个文件使用下面的代码:

$file = $_FILES['photo1']['name'];
$ext = pathinfo($file, PATHINFO_EXTENSION);
$photo = "newfile_".time().rand(5, 15).".".$ext
$targetx = $target . $photo;

为什么不使用时间戳?你确定它是独一无二的……因为如果两个图像有相同的随机序列呢?

可以使用md5()等散列函数。只需将此函数应用于上传的文件名

试试这个:

$temp = explode(".", $_FILES["image"]["name"]);
$extension = end($temp);
$newfilename = time().rand().".".$extension;
$target_Path = $path_to_image_directory.basename($_FILES['url']['name']);
if(preg_match('/[.](jpg)|(jpeg)|(gif)|(png)$/', strtolower ($_FILES['url']['name']))) {
        move_uploaded_file( $_FILES['url']['tmp_name'], $target_Path );
}
$extention = explode(".",$_FILES['url']['name']); // Or use str function
################### end code for move  #############################
$name = $imageName. "-" . RAND(10,100) . "." . $extention[1] ;
#####################################renaming the file ################
rename($path_to_image_directory.basename($_FILES['url']['name']), $path_to_image_directory.$name  );