Gina DiSanto
Gina DiSanto

Reputation: 1

How do I create a unique file name for my image uploader?

I have a form that has the option to upload images.

All is working fine, however, I need to makes those images uploaded have a unique name or number before/after original file name as to not overwrite another image that has the same name.

Here is my form - http://hoffwebsites.com/lfm_aow_form/application.php

I have tried using PHP code in my action/mailing script but nothing works for me.

Here is my file uploader code.

<b>Please attach two or three digital photos of your work</b><br><br>
<i>Photo #1</i><br>
<input type='file' name='file_upload'><br><br>
<i>Photo #2</i><br>
<input type='file' name='file_upload2'><br><br>
<i>Photo #3</i><br>
<input type='file' name='file_upload3'><br><br>

Here is the action/mailing php code that handles the file uploads and formats it in the form response email a person would receive after submission.

if ($_FILES["file_upload"]["name"] == "") {} else 
{ $message .= "Photo #1 \n http://hoffwebsites.com/lfm_aow_form/uploaded_files/"; }


$message .= $_FILES["file_upload"]["name"]; 
$message .= "\n\n";

// Check filesize
if($_FILES['file_upload']['size'] > 2097152){
    die('<center><font size=\"3\"><strong><u>Upload Error</u></strong></font>
<br>
<br>
<b>Your File Size is bigger then the maximum allowed - 2 MB.<br>
Please upload a smaller file.</b>
<br><br>
<a href="javascript: history.go(-1)">< Back</a>
<br></center>');
}


// Upload file
if(!move_uploaded_file($_FILES['file_upload']['tmp_name'], 'uploaded_files/' . $_FILES['file_upload']['name'])){
}

if ($_FILES["file_upload2"]["name"] == "") {} else 
{ $message .= "Photo #2 \n http://hoffwebsites.com/lfm_aow_form/uploaded_files/"; }


$message .= $_FILES["file_upload2"]["name"]; 
$message .= "\n\n";

// Check filesize
if($_FILES['file_upload2']['size'] > 2097152){
    die('<center><font size=\"3\"><strong><u>Upload Error</u></strong></font>
<br>
<br>
<b>Your File Size is bigger then the maximum allowed - 2 MB.<br>
Please upload a smaller file.</b>
<br><br>
<a href="javascript: history.go(-1)">< Back</a>
<br></center>');
}

// Upload file
if(!move_uploaded_file($_FILES['file_upload2']['tmp_name'], 'uploaded_files/' . $_FILES['file_upload2']['name'])){
}

if ($_FILES["file_upload3"]["name"] == "") {} else 
{ $message .= "Photo #3 \n http://hoffwebsites.com/lfm_aow_form/uploaded_files/";  }


$message .= $_FILES["file_upload3"]["name"]; 
$message .= "\n\n";

// Check filesize
if($_FILES['file_upload3']['size'] > 2097152){
    die('<center><font size=\"3\"><strong><u>Upload Error</u></strong></font>
<br>
<br>
<b>Your File Size is bigger then the maximum allowed - 2 MB.<br>
Please upload a smaller file.</b>
<br><br>
<a href="javascript: history.go(-1)">< Back</a>
<br></center>');
}

// Upload file
if(!move_uploaded_file($_FILES['file_upload3']['tmp_name'], 'uploaded_files/' . $_FILES['file_upload3']['name'])){
}

Please help with making these files uploaded have a unique name as to not overwrite another file.

Upvotes: 0

Views: 679

Answers (5)

Harvey Fletcher
Harvey Fletcher

Reputation: 104

Generate a filename using a hash of the current file name and the microtime (unix timestamp with microseconds), which is never repeated.

For example

$fileName = hash( 'sha512', $_FILES['file_upload2']['name'] . microtime() );

that will return you something along the lines of

a1758196cd3949485509be0d423d1ff85ada7857ab77cd77f6666107fce5b45dca01e42563f2925f136b677a7d169e100663c4eb705ccd742b8d3885d24ac005

Then you can add your file extension back on the end of that and it will be a unique filename.

$fileName = $_FILES['file_upload2']['name'];
$fileSplit = explode( '.', $fileName );
$fileName = hash( 'sha512', $fileName . microtime() ) . '.' . end( $fileSplit );

You have asked me to provide you with an example using your code. However, if I did this, you would not learn anything. So here is what you need to do to get this to work.

Create a function with my code provided. Call it something like generateUniqueFileName()

function generateUniqueFileName( $currentFileName = "" ){

}

Inside that function, place the code which creates the unique file name hash

function generateUniqueFileName( $currentFileName = "" ){
    //Explode the file name, so that we can get the file extension
    $fileSplit = explode( '.', $currentFileName );

    //Generate a unique name hash
    $fileName = hash( 'sha512', $currentFileName . microtime() ) . '.' . end( $fileSplit );

    //Return the unique file name hash
    return $fileName;
}

Where you are calling the move_uploaded_file() function, replace the second parameter to use this new function to generate a new file name. I have done the first one for you.

move_uploaded_file($_FILES['file_upload']['tmp_name'], 'uploaded_files/' . generateUniqueFileName( $_FILES['file_upload']['name'] ) );

Good luck, if you have any questions, please ask them in the comments and I will do my best to answer.

Upvotes: 1

scdnzhao
scdnzhao

Reputation: 1

  $extension=pathinfo($_FILES['file_upload']['name'],PATHINFO_EXTENSION);
  $file_name=$_FILES['file_upload']['name'].microtime();
  $unique_name=hash("md5",$file_name);
  move_uploaded_file($_FILES["file_upload"]["tmp_name"],
  "uploaded_files/" . $unique_name.".".$extension);

Upvotes: 0

kiske
kiske

Reputation: 430

This way you can create a unique name for you uploaded file without worring about hashes matching against diferent files, or names, the probability is very very low, but it can happen...

function createFileUuid($fname) {
    $fnameParts = explode('.', $fname);

    $uuidV4 = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );

    return $uuidV4 . '.' . end($fnameParts);
}

$fname = NULL;

do {
    $fname = createFileUuid($_FILES['file_upload']['name']);
} while (file_exists('uploaded_files/' . $fname));

// in this point $fname is unique...

Upvotes: 0

ABODE
ABODE

Reputation: 1018

To create a unique filename for an image, you need to first check if the image is already existing in the location before giving the file a name.

you can make use of this simple code

//Define the document root
  //live server use this
  $sitedoc = $_SERVER['DOCUMENT_ROOT'];

  //localhost server use this     
  $sitedoc = $_SERVER['DOCUMENT_ROOT']."/name_of_your_project";

  $filename = $_FILES["file_upload"]["name"];  
  $doc = $sitedoc."/documents/".$filename; 

  if (file_exists($doc)) {
    $actual_name = pathinfo($filename,PATHINFO_FILENAME);       
    $extension = pathinfo($filename, PATHINFO_EXTENSION);
    //This is your new file name
    $filename = $actual_name.time().".".$extension;        
    //New image location
    $doc = $sitedoc."/documents/".$filename;           
   }
   //Do the upload here
   move_uploaded_file($_FILES["file"]["tmp_name"], $doc)

Upvotes: 0

Detritus
Detritus

Reputation: 357

You could append a hash to the file name. See: https://www.php.net/manual/en/function.hash-file.php

This would hash the contents of the file giving you filename_<MYHASH>.ext

This doesn't ensure a file is not overwritten as two files with the same contents will have the same hash value.

Note: While it is rare, it is possible that two very different files may generate the same hash.

Upvotes: 0

Related Questions