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>