Home > Chủ đề khác > Renaming PHP Uploads

Renaming PHP Uploads

January 29th, 2008

Previously in our script allowing files to be uploaded from the browser and saved to the hosting via PHP, we mentioned it was possible to rename the files to something random to prevent people uploading files with the same name and overwriting each other’s files. In this script we will explore that further.

<form enctype="multipart/form-data" action="upload.php" method="POST">
Please choose a file: <input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>

The first thing we must do, is allow the user to upload a file. We can do that by placing this HTML on any page we want to allow them to upload from.

This code is in a file separate from our PHP. It points to a file called upload.php, however if you save your PHP by a different name you should change it here.

 

Finding the Extention

Next we will use a function explained here, to look at the file name and take off the extension for us to use later when we reassign it a new name.

 

<?php
//This function separates the extension from the rest of the file name and returns it
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}

//This applies the function to our file
$ext = findexts ($_FILES['uploaded']['name']) ;

   

 

  

A Random File Name

//This line assigns a random number to a variable. You could also use a timestamp here if you prefer.
$ran = rand () ;

//This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended.
$ran2 = $ran.".";

//This assigns the subdirectory you want to save into… make sure it exists!
$target = "images/";

//This combines the directory, the random file name, and the extension
$target = $target . $ran2.$ext;

This code uses the rand () function to generate a random number as the file name. Another idea is to use the time () function so that each file is named after its timestamp.

 

Saving the file with the new name

if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file has been uploaded as ".$ran2.$ext;
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>

Finally this code saves the file (with its new name) onto the server. It also tells the user what it is saved as. If there is a problem doing this, an error is returned to the user. Other features such as limiting files by size or restricting certain file types and also be added to this script if you choose.

Bài viết liên quan

Chủ đề khác

  1. No comments yet.
  1. No trackbacks yet.