2

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!

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
kenny
  • 438
  • 4
  • 14

3 Answers3

2

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

?>
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • This is perfect. Thank you so much for your time and help. – kenny May 29 '16 at 22:56
  • What will happen if he has a lot of visitors that happen to upload pictures at the exact same moment? I mean, your solution is good, but I know random generators tend to get in trouble when that happens. – icecub May 29 '16 at 23:28
  • @icecub do you know the probability of having the same 10 characters string based on 23 random characters? `41426511213649` – Pedro Lobito May 29 '16 at 23:52
  • Very high considdering that functions like `str_shuffle` are usually based on an algorithm using time or microtime. When used by 2 different processes at the exact same time, the result will be the same for both. Of course this would be false if `str_shuffle` doesn't rely on time. – icecub May 30 '16 at 00:03
  • @icecub I'll give you an up vote but I've to go. GL. – Pedro Lobito May 30 '16 at 00:06
  • 1
    Thanks, but I wasn't looking for an upvote. I was actually looking to learn something :) Cause I might missunderstand the way it works and don't want to continue with false information. – icecub May 30 '16 at 00:10
1

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

?>
icecub
  • 8,615
  • 6
  • 41
  • 70
0

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.

Community
  • 1
  • 1
Ilias
  • 86
  • 1
  • 13