Jump to content

Renaming Uploaded Files


Paws

Recommended Posts

I've been playing with an upload form and I want it the rename the uploaded file so you don't get files with dulpicate names. But I haven't had much sucess.

 

if (isset($_POST['submit'])) {
$target = "uploads/";
$temp_dir = $_FILES['file']['tmp_name'];
$file_name = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
try
{
   if(!preg_match('/(gif|jpe?g|png|zip|css|js|psd)$/i', $file_name))	      
   {
   	throw new Exception('Invalid file type.');
   	exit;
   }
   elseif($_FILES['file']['size'] > 3000000)
   {
      throw new Exception('File is too big.');
      exit;
   }
	move_uploaded_file($temp_dir, $target . $temp_dir);
	$status = 1;
}

catch(Exception $e)
{
	echo $e->getMessage();
}

}

 

Can somebody please help me?

Link to comment
https://forums.phpfreaks.com/topic/183328-renaming-uploaded-files/
Share on other sites

this line is no good:

 

move_uploaded_file($temp_dir, $target . $temp_dir);

 

change/add the following:

 

$ext = pathinfo ($file_name, PATHINFO_EXTENSION);
$file = pathinfo ($file_name, PATHINFO_FILENAME);
$file_name = md5 (rand (0, 99999) . time () . $file) . $ext;

 

then:

 

move_uploaded_file($temp_dir, $target . $file_name);

 

i would also use an array to store the allowed file types instead of using preg_match():

 

<?php
$bad_file_types = array ('image/jpeg','image/gif','application/x-javascript'); //etc...

if (in_array ($_FILES['file']['type'], $bad_file_types))
{
     //throw your error;
}
else
{
     //continue;
}
?>

 

reference for MIME types: Array of MIME types

Hi Mate,

 

You could append the current time to the uploaded file for example:

 

// Find out what ther files extension is, anything after the (.)
$fileExtension = substr(strrchr($file_name, '.') ,0);
$fileExtension = strtolower($fileExtension);

// The new file name
$newFileName = $file_name . time() . $fileExtension;

 

:)

 

Graham

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.