Question

Possible Duplicate:
Unique key generation

How to automaticly make a new name of file when you upload it to server?

I upload a picture file with < input type="file" / >. File has name picture_1.jpg. But I'd like to store it in filesystem with name like this ec0b4c5173809b6aa534631f3207.jpg? How such new names are created? Is some special script/generator used to make such names?

For example picture in FB: http:// a3.sphotos.ak.fbcdn.net/hphotos-ak-snc6/190074_10150167009837952_8062627951_8311631_4439729_n.jpg.

The name of it is 190074_10150167009837952_8062627951_8311631_4439729_n.jpg. But original name was different for sure. So I'd like to change the name of uploaded file the same way. How is it possible?

Was it helpful?

Solution

In PHP I use uniqid() for naming files that I store from uploads

If you want an extra long or seemingly more random id, you can sha1() or md5() the uniqid to create a hash.

You could of course also use those two methods to create a hash of the filename.

For example, the following code can be used to generate a new name for a file

$file = 'somefile.jpg';
$new_name = uniqid();
$new_name .= '.'.pathinfo($file,PATHINFO_EXTENSION);

OTHER TIPS

You didn't mention what programming language you are using.

in PHP, that cryptic name and original filename can be found on array $_FILES.

let's assume your form's element name is userfile, you can get that cryptic name from basename($_FILES['userfile']['tmp_name']) and the original name from basename($_FILES['userfile']['name'])

Visit here for more information : http://www.php.net/manual/en/features.file-upload.post-method.php

You could MD5 the name to create a string without spaces or dots: md5($filename) (http://php.net/md5) although I'm not sure that was what you were asking?

Edit: you could also use uniqid() (http://php.net/manual/en/function.uniqid.php)

You just rewrite the name of the file upon moving it from the temporary files on the server, to the location you want to move it to.

move_uploaded_file($_FILES['userfile']['tmp_name'], $filePN)

Where &filePN is the path and name of where you want to move the file to.

the special script that you're talking about, however, can be a multitude of things from an MD5 hash of the input name, to an incremented number to prevent overwrites.

Looks like a GUID.

If you are an ASP.NET programmer, use something like this:

string filename = new Guid().ToString() + ".jpg";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top