Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is a better option for random name of file on disk sha1 or uniqid?

To store uploaded files by users on remote server inside disk folder I change the name of file to

$filename = '/tmp/foo.txt';
$newName = sha1_file($filename); // 40 characters 
//or I can do
$newName = uniqid($filename) // 13 characters 

Which is a more robust method for new name that is not likely to fail ?? Thanks.

like image 350
Mr Coder Avatar asked Jun 03 '11 08:06

Mr Coder


3 Answers

A better solution is to use tmpfile() or tempnam(). Either one is guaranteed to create an unused file that won't collide and can't be "intercepted" by rogue processes changing permissions on you. tmpfile() automatically deletes the file when it's closed, whereas tempnam() keeps it around

http://www.php.net/manual/en/function.tmpfile.php

http://www.php.net/manual/en/function.tempnam.php

like image 78
Thomas Minor Avatar answered Nov 09 '22 15:11

Thomas Minor


Neither should give names which collide. sha1_file is a lot more compute intensive, but it has the useful property that if two users upload exactly the same file, it will be given the same name and you store it only once. If you don't expect a lot of people to upload the same file, or don't care about storing it twice, uniqid will run a lot faster.

like image 1
Matt Avatar answered Nov 09 '22 16:11

Matt


In either cases you want to check whether the file already exists. If you want to be 100% safe and the files are not too big then just use

sha1_file($filename);

This will pull the SHA-1 for the whole file so even if the file already exists the contents is the same.

Peace

like image 1
Ben Avatar answered Nov 09 '22 16:11

Ben