如何重命名图像或向图像添加随机数以创建唯一名称

时间:2014-05-06 10:02:48

标签: php image rename

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

5 个答案:

答案 0 :(得分:1)

对每个文件使用以下代码:

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您可以使用一些哈希函数,如md5()。只需将此功能应用于上传文件的名称即可。

答案 3 :(得分:0)

试试这个:

$temp = explode(".", $_FILES["image"]["name"]);
$extension = end($temp);

$newfilename = time().rand().".".$extension;

答案 4 :(得分:0)

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