7

Okay im using a snippet I found on google to take a users uploaded image and put it in my directory under Content

But Im worried about duplicates so I was going have it upload the image as a Random number

well here is my code you can probably understand what im going for through it anyways

<label for="file">Profile Pic:</label> <input type="file" name="ProfilePic" id="ProfilePic" /><br />

<input type="submit" name="submit" value="Submit" />

$ProfilePicName = $_FILES["ProfilePic"]["name"];
$ProfilePicType = $_FILES["ProfilePic"]["type"];
$ProfilePicSize = $_FILES["ProfilePic"]["size"];
$ProfilePicTemp = $_FILES["ProfilePic"]["tmp_name"];
$ProfilePicError = $_FILES["ProfilePic"]["error"];

$RandomAccountNumber = mt_rand(1, 99999);  
echo $RandomAccountNumber; 
move_uploaded_file($ProfilePicTemp, "Content/".$RandomAccountNumber.$ProfilePicType);

And then basicly after all this Im going try to get it to put that random number in my database

Someone gave me a new snippet that looks like it will do what I want but now the file isnt making it all the way to my directory

$RandomAccountNumber = uniqid();
echo $RandomAccountNumber;

move_uploaded_file($ProfilePicName,"Content/".$RandomAccountNumber);
bush man
  • 147
  • 2
  • 2
  • 8

5 Answers5

20

try using the php uniqid method to generate the unique id you need

http://php.net/manual/en/function.uniqid.php

$RandomAccountNumber = uniqid();
move_uploaded_file($ProfilePicTemp, "Content/" . $RandomAccountNumber);
DiverseAndRemote.com
  • 19,314
  • 10
  • 61
  • 70
  • hahah Thank you let me try to get this to work ill message you if I have any questions – bush man Nov 20 '12 at 22:54
  • hmmm I changed it to this $RandomAccountNumber = uniqid(); echo $RandomAccountNumber; move_uploaded_file($ProfilePicName,"Content/".$RandomAccountNumber); But now the file isnt making it to the directory file?? – bush man Nov 20 '12 at 23:12
  • @bushman, what happened to `.$ProfilePicType`? you removed it? Also make sure you have write permissions in that directory – DiverseAndRemote.com Nov 20 '12 at 23:14
  • @bushman, I think you need to leave it as `move_uploaded_file($ProfilePicTemp, "Content/".$RandomAccountNumber.$ProfilePicType);` since you need to find the file by using `$ProfilePicTemp` – DiverseAndRemote.com Nov 20 '12 at 23:15
  • hmm naw I used what you said and im getting these errors Warning: move_uploaded_file(Content/50ac1204a6921image/jpeg) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/content/34/9587634/html/MYDOMAIN.COM/Upload.php on line 208 Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/home/content/34/9587634/tmp/phpPp3mDX' to 'Content/50ac1204a6921image/jpeg' in /home/content/34/9587634/html/MYDOMAIN.Com/Upload.php on line 208 – bush man Nov 20 '12 at 23:30
  • The problem is the pictype is actually mime type which contains `/` in it. See me updated answer – DiverseAndRemote.com Nov 20 '12 at 23:33
  • hmm now they are making it through but they are loosing there file type so it come through as 5032ioifh random junk but not 5032ioifh.jpg Sorry, I know your probably sighing right now im just a noob trying to grasp this but I think im hooked lol – bush man Nov 20 '12 at 23:40
  • Yup, your question was about the unique id. Your second question now is "How do I get the file extension when given a MIME type" which you can find an answer to at http://stackoverflow.com/questions/1147931/how-do-i-determine-the-extensions-associated-with-a-mime-type-in-php – DiverseAndRemote.com Nov 20 '12 at 23:43
  • hmm okay ill try to mess with that but I thought I could just add it as $ProfilePicType while moving it from the temp I mean I already know the file type. – bush man Nov 20 '12 at 23:57
5

When I upload images, I usually save it as the sha1() of the image's contents (sha1_file()). That way, you get two birds with one stone: You'll never (if you do, go fill out the closest lottery) get duplicate file names, AND, you'll prevent duplicate images (because duplicate images would have the same checksum).

Then, you have a database to sort out which image is which, and correctly display them to the user.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • 2
    I think this method would be bad. What if two users upload the same LOL cat and then one deletes it – DiverseAndRemote.com Nov 20 '12 at 22:50
  • @OmarJackman: It all depends on usage of course, you can make the file number user specific by adding a prefix, or grouping them into folders. – Madara's Ghost Nov 20 '12 at 22:51
  • @MadaraUchiha do you use `sha1` or `sha1_file`? Just curious – Yes Barry Nov 20 '12 at 22:56
  • @mmmshuddup: I use `sha1_file()`. Many people (for some strange reason) like to use `sha1(file_get_contents())`. – Madara's Ghost Nov 20 '12 at 22:57
  • @MadaraUchiha Oh ok. yeah that's weird. I have actually never seen this method that's why I was curious. You should provide a little snippet :) – Yes Barry Nov 20 '12 at 22:58
  • @MadaraUchiha probably because they don't realize that `sha1_file` exists – DiverseAndRemote.com Nov 20 '12 at 22:59
  • @OmarJackman yeah most likely. it's a nice little trick I might use this one later if I need random/unique image names. – Yes Barry Nov 20 '12 at 23:00
  • I really must say though that this solution seems more complicated than it needs to be. This is what the `uniqid()` method was made for. No need to read the contents of a file and execute `sha1` just to get a unique id. – DiverseAndRemote.com Nov 20 '12 at 23:04
  • @OmarJackman I totally agree, but this is still a nice method. – Yes Barry Nov 20 '12 at 23:05
  • 1
    @OmarJackman: Unique ID is random, this isn't. I used this solution when I had a gallery project to store hundreds of thousands of images. You needed some sort of system for it, or you'd never leave that code alive. – Madara's Ghost Nov 20 '12 at 23:05
  • @MadaraUchiha that's a lot of images. Yeah in a situation like that, "_more complicated than it needs to be_" doesn't carry as much weight. I personally just let keep the original filename and append a (1) to the end if there are dupes. It's worked for me so far with no issues. But I'll keep this method in mind! – Yes Barry Nov 20 '12 at 23:09
5

This is what I use when uploading pictures: a combination of session_id(), time() and a random string:

$rand = genRandomString();
$final_filename = $rand."_".session_id()."_".time();

function genRandomString() 
{
    $length = 5;
    $characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWZYZ";

    $real_string_length = strlen($characters) ;     
    $string="id";

    for ($p = 0; $p < $length; $p++) 
    {
        $string .= $characters[mt_rand(0, $real_string_length-1)];
    }

    return strtolower($string);
}

I hope this help.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
Frank
  • 106
  • 2
  • Since session ids can contain commans, would there be any issues with a comma in a filename using this method? – kojow7 Sep 09 '15 at 03:50
3

random != unique

No matter what method you use to generate a 'random' file name you're probably going to want to do this to avoid collisions.

$path = '/path/to/directory/';
do {
    $filename = some_function();
} while( file_exists($path.$filename) );

It's not super-necessary, but if you're just looking for peace of mind in case of a one-in-a-million filename collision then those couple extra lines will do the trick.

Sammitch
  • 30,782
  • 7
  • 50
  • 77
  • Combine this with [Omar Jackman's answer](http://stackoverflow.com/a/13483456/486233) and it would be the perfect answer. – Yes Barry Nov 20 '12 at 22:54
1

One of my favorite Coding Horror articles addresses why this approach is dumber than it looks, and you should use something like uniqid instead of mt_rand(1, 99999);...

Dean Rather
  • 31,756
  • 15
  • 66
  • 72