wobsoriano
wobsoriano

Reputation: 13452

Storing image in a folder laravel

I have a small piece of code that will get the request input file from the form and will move it to a folder. Here it is:

$destinationPath = 'uploads';

$filename = $file->getClientOriginalName();

$upload_success = $file->move($destinationPath, $filename);

Yes, the code above works but then what I wanted to do is each time I upload an image, it will have a unique name so it wouldn't overwrite any picture in the folder. For now this is what I did:

function generateRandomString($length = 8) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

$destinationPath = 'uploads';
$rand = md5(generateRandomString());
$filename = $rand."_".$file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);

This will output something like 7c724458520a11c68747793c86554127_Jellyfish.jpg but it looks untidy. Is there a trick for this? Thank you.

Upvotes: 3

Views: 130

Answers (3)

wobsoriano
wobsoriano

Reputation: 13452

I've managed to solve my problem. First by removing md5 as suggested by Abdulla and then by doing this:

$destinationPath = 'uploads';
$rand = generateRandomString();

$file_list = File::files('uploads'); //returns an array of all of the files in a given directory.

do {
  $filename = $rand."_".$file->getClientOriginalName();
} while(in_array("uploads/".$filename, $file_list)); //keep generating a string until it doesn't exist in the given directory.

$upload_success = $file->move($destinationPath, $filename); //move the file

Upvotes: 1

Abdulla Nilam
Abdulla Nilam

Reputation: 38609

just remove md5 on here $rand = md5(generateRandomString());

Because you generate a random string then hashed it

Upvotes: 2

Mihkel Allorg
Mihkel Allorg

Reputation: 989

One of the more common ways to create unique file names is using time.

Also you could check this:

https://laracasts.com/discuss/channels/general-discussion/how-to-generate-long-unique-name-for-filename

Upvotes: 1

Related Questions