How to make file_get_contents return an unique result

225 views Asked by At

I am new to php and would like to ask you for some help returning an unique result from file_get_contents(). The reason is I want to give each photo an unique name, so that later it will be possible to delete just one of them and not all.

$file =addslashes(file_get_contents($_FILES['image']['tmp_name'][$key]));

Unfortunately time() and microtime() doesn't help in this situation.

2

There are 2 answers

3
Bluesky On

Maybe this will help you: http://php.net/manual/en/function.uniqid.php

uniqid();

$imageName = $imageName . '_' . uniqid();

1
Roger Gee On

Why not just generate the SHA-1 of the content and use that as the file name (sort of like how git stores objects in a repository's loose object database)? I typically don't like to insert blobs into the RDBMS; it's a little clunky and you have to make sure the blob field has enough space for the kind of file sizes you're expecting to work with. Plus, the filesystem is optimized to handle, well, files. So it makes sense to keep a special directory on the server to which the Web server has write access. Then you write the files there and store references to them in the database. Here's an example:

// Read the contents of the file and create a SHA-1 hash signature.
$tmpPath = $_FILES['image']['tmp_name'];
$blob = file_get_contents($tmpPath);
$name = sha1($blob) . '.img'; // e.g. b99c6e26c3775fca9918ad614b7be7fe4fd7bee3.img

// Save the file to your server somewhere.
$dstPath = "/path/to/imgdb/$name";
move_uploaded_file($tmpPath,$dstPath);

// TODO: insert reference (i.e. $name) into database somehow...

And yes, researches have broken SHA-1, but you could easily write some safeguards against that if you're paranoid enough (e.g. check for an existing upload with the same hash; it the content differs, just mutate/append to the name a little to change it). You aren't identifying the image on the backend by its content: you just need a unique name. Once you have that, you just look it up from the DB to figure out the file path on disk corresponding to the actual image data.

If you expect the image files to be pretty large, you could limit how much you read into memory using the 4th parameter to file_get_contents().