Upload and Rename a File with PHP

Eventually every programmer will be required to find a way to upload a file to a web server. I recently started a project that required a way for me to upload a word doc to a web server, which, in turn, required me to write a upload and rename script in PHP.

See my updated version of this script called A Better PHP Upload and Rename Script.

So, here are the steps I went through to get a word doc to upload to a directory on my web server.

Step 1: Build the Form

I am just going to assume you know how to build an upload form in HTML. But just in case, here is the code I used:

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data" name="file_upload">
	<input type="file" name="file" id="file">
	<input type="hidden" name="execute" id="execute">
	<input type="submit" name="Submit" id="Submit" value="Submit">
</form>

This form, of course, lets me post a file to a temp directory on the web server. Once our file is posted, we then validate the file type, size, and if everything checks out, move the file to its final destination.

Step 2: The Code

Here is the code that puts out file on the server, checks the file type, and does some error reporting.

<?php
// Upload and Rename File
if (isset($_POST['execute'])) {
 
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // strip extention
$file_ext = substr($filename, strripos($filename, '.')); // strip name
$filesize = $_FILES["file"]["size"];
 
	if (($file_ext == ".doc" || $file_ext == ".docx")  &&  ($filesize < 200000)) {
		// rename file
		$newfilename = md5($file_basename) . $file_ext;
 
		if (file_exists("upload/" . $newfilename)) {
			// file already exists error
			$error = "You have already submitted this file.";
		} else {
			move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $newfilename);
			echo "File uploaded successfully.";
		}
	} elseif (empty($file_basename)) {
		// file type error
		$error = "Please select a file to upload.";
	} else {
		// file selection error
		$error = "Only doc, docx, rtf, pdf, and txt files can be submitted online.";
		unlink($_FILES["file"]["tmp_name"]);
	}
}
?>

Everything is this code is commented pretty well. The important lines of code here are where the new file name is built ($newfilename) and where the file, if valid, is moved to its final location (move_uploaded_file()). Make sure you set the final file directory in the move_uploaded_file() command. Otherwise, the script will fail.

Added Bonus: This Script Can Upload Anything

Just so you know, you can upload anything to a web server with this script. All you need to do is change the allowed extensions near $file_ext == “.doc”.


Comments

  1. Husnain said on May 5, 2009

    Hi,
    It works fine, but this code has a problem, when a file is uploaded twice with same name it does not work. Please inform where to change code.
    Thanks

  2. Zac said on May 5, 2009

    Hi Husnain,

    You should have no problems changing the code to work with the same file over and over. Try changing this line:

    $newfilename = md5($file_basename) . $file_ext;

    to something like

    $newfilename = md5(time() . $file_basename) . $file_ext;

    Let me know if that works for you.

  3. Saguenay said on May 23, 2009

    Great tutorial! Thanks!

  4. YooNet said on June 25, 2009

    Hi,

    Nice script, how do i show the url to the file?

    Many Thanks!

  5. Zac said on June 25, 2009

    Hi YooNet,

    Try adding this to line 20–it should give you a path to the file:

    echo “upload/” . $newfilename;

  6. aleks said on August 8, 2009

    very well said! thanks for this…it really helps me a lot :)

    kind regards,
    ~aleks

  7. SHW said on September 11, 2009

    Thanks, man. This was exactly what I was looking for!
    You helped me a lot. I just wanted to let you know :)
    Greetings from Germany

  8. Asanka lakmal said on October 28, 2009

    Great work. Thanks very much

    Asanka

  9. Juussi said on February 2, 2010

    Hello. Thanks for this.

    Is it possible to ‘post’ also a wanted new file name and rename the sent file in server site?

  10. ajay sarweai said on April 15, 2011

    Thanks.

  11. brandon said on May 3, 2011

    tnx

  12. Jannis said on June 15, 2011

    Nice script! Very useful… ;)

  13. Adnan said on June 30, 2011

    your code does not work properly
    plz check it

  14. Zac said on July 1, 2011

    Hi Adnan,
    I’m fairly certain the script works. I test all code before I publish it. Please give it another shot.

  15. Rafael said on August 2, 2011

    Code works flawlessly. I made my own modifications but this saved me a ton of time. Thanks Zac!

  16. Junaidu said on September 5, 2011

    its really works, thanks onceagain.
    But one more help. How do i add the new name to the Database?

    THANKS IN ADVANCE

Add Your Comment