Upload images via php using unique file names

I am currently writing a mobile application using phonegap. One of the few functions that I would like to get from this application is the ability to capture an image and upload it to a remote server ...

I currently have an image capture and upload / email part that works fine with compiled apk ... but in my php I currently call the image "image [insert random number from 10 to 20] ... Problem here is what numbers can be repeated and images can be overwritten ... I read and thought about just using rand () and picking a random number from 0 to getrandmax (), but I feel like I can have the same the probability of overwriting the file ... I need the image to be uploaded to the server with a unique name every time, no matter what ... so php script will check to see that the server already has and writes / uploads an image with a unique name ...

any ideas other than "rand ()"?

I also thought about possibly naming each image ... img + date + time + random 5 characters that will contain letters and numbers ... so if the image was taken using the application at 4:37 a.m. March 20, 2013, the image will be called something like "img_03-20-13_4-37am_e4r29.jpg" when uploading to the server ... I think this might work ... (if this is not the best way), but I quite new in php and didn't understand how to write something like that ...

my php looks like this:

print_r($_FILES); $new_image_name = "image".rand(10, 20).".jpg"; move_uploaded_file($_FILES["file"]["tmp_name"], "/home/virtual/domain.com/public_html/upload/".$new_image_name); 

Any help is appreciated ... Thanks in advance! Also, please let me know if there is any additional information that I can ignore ...

+6
source share
4 answers

You might want to consider the PHP uniqid() function. Thus, the code you proposed will look like this:

 $new_image_name = 'image_' . date('YmdHi-s') . '_' . uniqid() . '.jpg'; // do some checks to make sure the file you have is an image and if you can trust it move_uploaded_file($_FILES["file"]["tmp_name"], "/home/virtual/domain.com/public_html/upload/".$new_image_name); 

Also remember that your random functions on the server are not random. Try random.org if you need something really random. Random random random.

UPD To use random.org from your code, you will need to execute some API requests on your servers. Documentation at this address is available here: www.random.org/clients/http/ .

Example call: random.org/integers/?num=1&min=1&max=1000000000&col=1&base=10&format=plain&rnd=new . Please note that you can change min , max and other parameters as described in the documentation .

In PHP, you can make a GET request to a remote server using the file_get_contents() function, cURL or even sockets. If you use shared hosting, outgoing connections should be available and enabled for your account.

 $random_int = file_get_contents('http://www.random.org/integers/?num=1&min=1&max=1000000000&col=1&base=10&format=plain&rnd=new'); var_dump($random_int); 
+16
source

You must use tempnam() to create a unique file name:

 // $baseDirectory Defines where the uploaded file will go to // $prefix The first part of your file name, eg "image" $destinationFileName = tempnam($baseDirectory, $prefix); 

The extension of your new file should be done after moving the downloaded file, i.e.:

 // Assuming $_FILES['file']['error'] == 0 (no errors) if (move_uploaded_file($_FILES['file']['tmp_name'], $destinationFileName)) { // use extension from uploaded file $fileExtension = '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); // or fix the extension yourself // $fileExtension = ".jpg"; rename($destinationFileName, $destinationFileName . $fileExtension); } else { // tempnam() created a new file, but moving the uploaded file failed unlink($destinationFileName); // remove temporary file } 
+5
source

Do you find using md5_file ? This way all your files will have a unique name and you won’t have to worry about duplicate names. But keep in mind that this will return the same string if the contents are the same.

There is also another way:

 do { $filename = DIR_UPLOAD_PATH . '/' . make_string(10) . '-' . make_string(10) . '-' . make_string(10) . '-' . make_string(10); } while(is_file($filename)); return $filename; /** * Make random string * * @param integer $length * @param string $allowed_chars * @return string */ function make_string($length = 10, $allowed_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') { $allowed_chars_len = strlen($allowed_chars); if($allowed_chars_len == 1) { return str_pad('', $length, $allowed_chars); } else { $result = ''; while(strlen($result) < $length) { $result .= substr($allowed_chars, rand(0, $allowed_chars_len), 1); } // while return $result; } // if } // make_string 
+1
source

The function will create a unique name before loading the image.

 // Upload file with unique name if ( ! function_exists('getUniqueFilename')) { function getUniqueFilename($file) { if(is_array($file) and $file['name'] != '') { // getting file extension $fnarr = explode(".", $file['name']); $file_extension = strtolower($fnarr[count($fnarr)-1]); // getting unique file name $file_name = substr(md5($file['name'].time()), 5, 15).".".$file_extension; return $file_name; } // ends for is_array check else { return ''; } // else ends } // ends } 
-1
source

All Articles