Giving uploaded images a unique name for mysqli

故事扮演 提交于 2020-02-04 04:37:25

问题


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!


回答1:


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);
}

?>



回答2:


PHP has a build in function to generate unique files on your server. This function is known as tempnam(). If you read the comments on that website carefully though, there is a small chance you'll get unwanted behaviour from that function if to many processes call it at the same time. So a modification to this function would be as follows:

<?php

function tempnam_sfx($path, $suffix){
    do {
        $file = $path."/".mt_rand().$suffix;
        $fp = @fopen($file, 'x');
    }
    while(!$fp);

    fclose($fp);
    return $file;
}

?>

Because the file is kept open while it's being created, it can't be accessed by another process and therefor it's impossible to ever create 2 files with the same name simply because a couple of your website visitors happened to upload pictures at the exact same moment. So to implement this in your own code:

<?php

function tempnam_sfx($path, $suffix){
    do {
        $file = $path."/".mt_rand().$suffix;
        $fp = @fopen($file, 'x');
    }
    while(!$fp);

    fclose($fp);
    return $file;
}

$uploaddir = 'pictures'; // Upload directory
$file = $_FILES['file']['name']; // Original file
$ext = pathinfo($path, PATHINFO_EXTENSION); // Get file extension

$uploadfile = tempnam_sfx($uploaddir, $ext);

move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".basename($uploadfile)."' WHERE user_id = '{$_SESSION['user']}'");
header("Location: index.php");

?>



回答3:


One way you could do this, is by generating a few random numbers (and possibly attaching them to current date in number format) and give the image the number sequence.

 if(isset($_POST['submitimage'])){
            //generate 3 sequences of random numbers,you could do more or less if you wish
            $randomNumber=rand().rand().rand();
            move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$randomNumber."jpg");
            $con = mysqli_connect("localhost","root","","database");
            $q = mysqli_query($con,"UPDATE users SET image = '".$randomNumber.".jpg' WHERE user_id = '".$_SESSION['user']."'");
             header("Location: index.php");
    }
?>

Note : you could also look into generating random strings if numbers are not your thing.



来源:https://stackoverflow.com/questions/37515620/giving-uploaded-images-a-unique-name-for-mysqli

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!