Search code examples
phpfile-rename

Giving uploaded images a unique name for mysqli


I want to allow users to upload images without conflicting problems that may be caused by multiple users uploading images that potentially have the same image name. I am stumped on how to execute this and I have no idea where to start..

Here is my code:

 if(isset($_POST['submitimage'])){
                move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$_FILES['file']['name']);
                $con = mysqli_connect("localhost","root","","database");
                $q = mysqli_query($con,"UPDATE users SET image = '".$_FILES['file']['name']."' WHERE user_id = '".$_SESSION['user']."'");
                 header("Location: index.php");
        }
?>

Any help would be amazing. Thank you!


Solution

  • My solution is to generate a random string for each uploaded file, i.e.:

    <?php
       if(!empty($_POST['submitimage'])){
                    //get file extension.
                    $ext = pathinfo($_FILES['file']['name'])['extension'];
                    //generate the new random string for filename and append extension.
                    $nFn = generateRandomString().".$ext";
                    move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$nFn);
                    $con = mysqli_connect("localhost","root","","database");
                    $q = mysqli_query($con,"UPDATE users SET image = '{$nFn}' WHERE user_id = '{$_SESSION['user']}'");
                     header("Location: index.php");
            }
    
    function generateRandomString($length = 10) {
        return substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
    }
    
    ?>