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.
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With