如何上传图片的随机名称?

时间:2018-08-27 12:30:27

标签: php image-uploading file-rename

在上载图像时,如何给图像取一个随机名称,而不是取当前图像的名称?

   if(isset($_FILES['image'])){
  $errors= array();
  $file_name = $_FILES['image']['name'];
  $file_tmp =$_FILES['image']['tmp_name'];
  $file_type=$_FILES['image']['type'];
  $file_name_array = explode('.',$_FILES['image']['name']);
  $file_ext=strtolower(end($file_name_array));

  $expensions= array("jpeg","jpg","png");

  if(in_array($file_ext,$expensions)=== false){
     $errors[]="extension not allowed, please choose a JPEG or PNG file.";
  }


  if(empty($errors)==true){
     move_uploaded_file($file_tmp,"uploads254/".$file_name);
  }else{
     print_r($errors);
  }strong text

3 个答案:

答案 0 :(得分:0)

有很多方法可以做到,我建议使用uniqid()

更改

move_uploaded_file($file_tmp,"uploads254/".$file_name);

move_uploaded_file($file_tmp, "uploads254/" . uniqid(rand(), true) . $file_ext;

答案 1 :(得分:0)

您可以使用php rand()函数生成随机字符串,并将其用作图像文件的名称。

function getRandomImageName($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $imageName = '';
    for ($i = 0; $i < $length; $i++) {
        $imageName .= $characters[rand(0, $charactersLength - 1)];
    }
    return $imageName;
}



if(isset($_FILES['image'])){
  $errors= array();
  $file_name = $_FILES['image']['name'];
  $file_tmp =$_FILES['image']['tmp_name'];
  $file_type=$_FILES['image']['type'];
  $file_name_array = explode('.',$_FILES['image']['name']);
  $file_ext=strtolower(end($file_name_array));
  $fileName = getRandomImageName(10);

  $expensions= array("jpeg","jpg","png");

  if(in_array($file_ext,$expensions)=== false){
     $errors[]="extension not allowed, please choose a JPEG or PNG file.";
  }


  if(empty($errors)==true){
     move_uploaded_file($file_tmp,"uploads254/".$fileName);
  }else{
     print_r($errors);
  }

答案 2 :(得分:0)

您可以将变量$file_name的值替换为rand()或您要使用的任何其他名称。