header
 
     
 
pixel
pixel pixel

Upload without overwriting existing files

When using HTML forms and PHP to upload files onto a website, there's always the danger that you'll overwrite existing files on the website. The following code checks if the uploaded file already exists and if so, prefixes the filename with a number and an underscore. Eg - "filename.txt" is renamed to "1_filename.txt". However, if "1_filename.txt" already exists, it increments the prefix until it finds an available filename. Eg - "2_filename.txt", "3_filename.txt", etc. Note - I've also included a line of code that uses a regular expression to remove any non-web friendly characters from the filename. This isn't necessary but often useful when the uploaded files are meant to be viewed on the web. Upload HTML form
<html>
  <head>
    <title>HTML Form for uploading image to server</title>
  </head>
  <body>
    <form name="upload" method="post" action="uploadresults.php" enctype="multipart/form-data">
      <input type="file" name="Image"><br> 
      <input type="submit" value="Upload Image">
    </form>
  </body>
</html>
uploadresults.php
<?php
// rename file to remove web-unfriendly characters
$OriginalFilename $FinalFilename preg_replace('`[^a-z0-9-_.]`i','',$_FILES['image']['name']);

// rename file if it already exists by prefixing an incrementing number
$FileCounter 1;

// loop until an available filename is found
while (file_exists'files/'.$FinalFilename ))
  
$FinalFilename $FileCounter++.'_'.$OriginalFilename;

move_uploaded_file $_FILES['image']['tmp_name'], "files/$FinalFilename" ) or die ("Could not copy");
?>

Unhelpful Helpful
Comments
Comment by discount Michael Jordan Shoes on 2010-09-17
Air Jordan Shoes are always so attractive, good quality can ensure the wearer's feet, not only that, the Michael Jordan Shoes has become a fashion, many young people are very fanatical Air Jordan. High price so many people can realize their dreams. Well now, our products directly from third-party products, so we can provide cheap Jordan Basketball Shoes and New Jordan Shoes, high quality, excellent service, come on, give yourself a choice. We offerAir Jordan 1, Air Jordan 2, Air Jordan 3,Air Jordan 4, Air Jordan 5, Air Jordan 6, Air Jordan 7, Air Jordan 8, Air Jordan 9, Air Jordan 10, Air Jordan 11 and so on!

Post a Comment
Name
Email
(optional)
Comment
RatingUnhelpful Helpful
Security Image* (this is just to prevent spam submissions)
Security Image