Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashing image names

Tags:

php

hash

sha

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?

like image 585
user3729576 Avatar asked Dec 14 '25 13:12

user3729576


2 Answers

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

like image 200
Cucu Avatar answered Dec 17 '25 02:12

Cucu


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();
like image 43
user2444499 Avatar answered Dec 17 '25 01:12

user2444499



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!