user3729576
user3729576

Reputation: 247

Hashing image names

I'm uploading images to S3 and I wish to create a unique name for each one uploaded.

I'm using intervention to make the image:

$img = Image::make($file->getRealPath());

Then I hash the image:

$name = hash('sha256', $img);

The problem is, when I upload the same image, it's given the same name.

How can I get around this?

Upvotes: 3

Views: 3801

Answers (4)

Cucu
Cucu

Reputation: 305

You should try to add a salt to it. Even appending the date/time should give you an unique name. Cheers!

PS (edit):

$data = Image::make($file->getRealPath())->encode('data-url'); 

$name = hash('sha256', $data . strval(time()));

First we encode the data in a "string way" so we can concatenate the time value as a string.

If you want extra "randomness" add a user cookie, username etc.

Final solution:

$data = implode('', file($file->getRealPath()));

$name = hash('sha256', $data . strval(time()));

Upvotes: 2

adesst
adesst

Reputation: 307

You could try add a rand()

hash('sha256', $img . rand(1,100) );

Upvotes: -1

Jacob Cohen
Jacob Cohen

Reputation: 1272

Best way to avoid this is by using a timestamp for each upload. Just combine the $img with current timestamp by using the time() function.

For example:

hash('sha256', $img+time());

Upvotes: 0

user2444499
user2444499

Reputation: 767

Have you considered using com_create_guid() to create a global unique identifier instead? This would give you a unique name for each file. For example:

$name = com_create_guid();

Upvotes: 1

Related Questions