0

I have a code to set members avatar / profile picture. works great, but just discovered it has an error when uploading pictures with same name as already existing file. How can i change the file name if it already exists? like a random MD5 string or something. Doesn't really mather as long as each string would be unique.

<?php
   if(isset($_FILES['image'])){
      $errors= array();
      $file_name = $_FILES['image']['name'];
      $file_size =$_FILES['image']['size'];
      $file_tmp =$_FILES['image']['tmp_name'];
      $file_type=$_FILES['image']['type'];
      $tmp = explode('.', $file_name);
      $file_ext = end($tmp);

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

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

      if($file_size > 2097152){
         $errors[]='File size must be excately 2 MB';
      }

      if(empty($errors)==true){
         move_uploaded_file($file_tmp,"images/uploads/".$file_name);
         echo "Success";
         //sets avatar
         $sql = "UPDATE users SET avatar = '$file_name' WHERE id = '$id'";
         $db->query($sql);
      }else{
         print_r($errors);
    }
   }
?>
<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="image" />
    <input type="submit" class="normal-btn" value="Upload"/>
    <a class="button2 fa fa-times" href="/profiles/remove-avatar.php"><div class="font">Remove</div></a>
</form>
Martin
  • 27
  • 6
  • 2
    Possible duplicate of [php Unique filename when uploading](http://stackoverflow.com/questions/8563958/php-unique-filename-when-uploading) – Rajdeep Paul Jun 18 '16 at 20:16
  • Also, take a look at [`tempnam()`](http://php.net/manual/en/function.tempnam.php) function. – Rajdeep Paul Jun 18 '16 at 20:17
  • @RajdeepPaul thanks! was able to fix the issue by using the uniqid() function. file wont be save as any specific file type but it works to set the profile picture – Martin Jun 18 '16 at 21:23

0 Answers0