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.


what do you mean by fail?

Written by Thilo

sha1_file() will be awfully slow on large files (and not unique for files with the same content, e.g., textual licence files). I would use uniqid() if only these 2 options are given. If file is linked to DB, you might think about using some ID from DB, which should be "unique enough". Another option would be to use date('Ymd-His-') . $n, with $n being 0 for the first file in that second, 1 for the second file etc. P.S. You should work on your accept rate - 67% is a bit low after asking 20 questions.

Written by binaryLV

@thilo by fail I mean stability of that function .

Written by jason bourne

But sha1_file is handy for 1) tracking duplicates 2) creating a balanced tree naming schema

Written by symcbean

Accepted Answer

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

Written by Thomas Minor
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the community.
It is licensed under cc-wiki