Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php Unique filename when uploading

I've a submit discussion form with image upload in my website. Now, I want to upload a unique file name when the user submits their image so that I can show the result of all images and can avoid duplicate file names.

How can I do this with php? If you need my form process code then I'll upload it.

like image 300
Umme Habiba Kanta Avatar asked Dec 19 '11 16:12

Umme Habiba Kanta


People also ask

How to upload file with unique name in PHP?

Sample code:$_FILES["img"]["name"]); Please try this one: // Make sure this imagePath is end with slash $imagePath = '/root/path/to/image/folder/'; $uniquesavename=time(). uniqid(rand()); $destFile = $imagePath .

What is move_ uploaded_ file in PHP?

Definition and Usage. The move_uploaded_file() function moves an uploaded file to a new destination. Note: This function only works on files uploaded via PHP's HTTP POST upload mechanism. Note: If the destination file already exists, it will be overwritten.

How to get upload file path in PHP?

php $dir = dirname(__FILE__); echo "<p>Full path to this dir: " . $dir . "</p>"; echo "<p>Full path to a . htpasswd file in this dir: " .


2 Answers

You can use the uniqid() function to generate a unique ID

/**
 * Generate a unique ID
 * @link http://www.php.net/manual/en/function.uniqid.php
 * @param prefix string[optional] <p>
 * Can be useful, for instance, if you generate identifiers
 * simultaneously on several hosts that might happen to generate the
 * identifier at the same microsecond.
 * </p>
 * <p>
 * With an empty prefix, the returned string will
 * be 13 characters long. If more_entropy is
 * true, it will be 23 characters.
 * </p>
 * @param more_entropy bool[optional] <p>
 * If set to true, uniqid will add additional
 * entropy (using the combined linear congruential generator) at the end
 * of the return value, which should make the results more unique.
 * </p>
 * @return string the unique identifier, as a string.
 */
function uniqid ($prefix = null, $more_entropy = null) {}
like image 95
John Magnolia Avatar answered Sep 18 '22 14:09

John Magnolia


You could use a timestamp in the date, that way you won't get the same filename/time twice.

Not certain exactly what your code looks like but you could do something like this:

$filename = uniqid() . $orig_filename;

Read this documentation on the PHP docs about uniqid for more information. It uses the datetime to output a unique identifier string.

like image 27
Batkins Avatar answered Sep 20 '22 14:09

Batkins