生成唯一的图像名称并保存到目标文件夹

时间:2017-04-02 03:10:11

标签: php jquery html

我有这个表单,您可以上传一张将用作个人资料照片的图片。图像的名称将注册到数据库,因此在将其注册到数据库之前使用唯一的名称作为图像的名称是明智的,以避免将来出现错误和内容。

这是我提出的代码:

function random_str($type = 'alphanum', $length = 8)
{
  switch($type)
  {
      case 'basic'    : return mt_rand();
          break;
      case 'alpha'    :
      case 'alphanum' :
      case 'num'      :
      case 'nozero'   :
              $seedings             = array();
              $seedings['alpha']    = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
              $seedings['alphanum'] = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
              $seedings['num']      = '0123456789';
              $seedings['nozero']   = '123456789';

              $pool = $seedings[$type];

              $str = '';
              for ($i=0; $i < $length; $i++)
              {
                  $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
              }
              return $str;
          break;
      case 'unique'   :
      case 'md5'      :
                  return md5(uniqid(mt_rand()));
          break;
  }
}

$key = random_str('alphanum', 12);


if(isset($_POST['upload'])) {
    $target = "profiles/".$key.basename($_FILES['image']['name']); 

    $image = $key.basename($_FILES['image']['name']);


    $sql = "UPDATE users SET img = '$image' WHERE idnumber = $idnumber";
    mysqli_query($con,$sql);

    if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        header("Location:home.php");
    } else {
        header("Location:error_uploading.php");
    }
}



唯一的问题是,例如图片的原始文件名是image1.png,它会生成名称sK1ls902nzAlimage1.png。我知道这有点矫枉过正,但我​​怎么能最终摆脱...image1.png呢?我的代码有什么好处吗?或者有更好的方法(更短的方式)吗?谢谢!

1 个答案:

答案 0 :(得分:0)

据推测,您希望从image1 删除sK1ls902nzAlimage1.png(删除分机无意义)

if(isset($_POST['upload'])) {
    # Get extension
    $ext     = pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION);
    # Create image file name
    $image   = "{$key}.{$ext}";
    # Create image path final destination
    $target  = "profiles/{$image}";
    # Check if the upload is successful
    $success = move_uploaded_file($_FILES['image']['tmp_name'], $target);
    # If successful, set home page, save to database
    if($success) {
        $path = "home";
        mysqli_query($con,"UPDATE users SET img = '{$image}' WHERE idnumber = {$idnumber}");
    }
    else
        $path = "error_uploading";

    header("Location: {$path}.php");
    exit;
}

这只会保存:

sK1ls902nzAl.png

如果你真的只想删除扩展名,那么这一行只需要:

# Will be sK1ls902nzAl vs sK1ls902nzAl.png
$image   = $key;