A Better PHP Upload and Rename Script

upload_arrowAn earlier post of mine provides a fairly good example of a PHP script that renames a file as you upload it to a server. In this post, I’ve decided to take another look at that type of script and make it easier to use. I’m going to break the code you’ll need into two parts: the HTML and the PHP. Once you have this script on your server, make sure you create a writable folder (I call mine “upload”) on your server to contain your uploaded files.

HTML

<form action="" method="post" enctype="multipart/form-data">
	<input type="file" name="file" id="file">
	<input type="submit" name="submit" id="Submit" value="Submit">
</form>

PHP

<?php
 
// Upload and Rename File
 
if (isset($_POST['submit'])) {
 
	$filename = $_FILES["file"]["name"];
	$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
	$file_ext = substr($filename, strripos($filename, '.')); // get file name
	$filesize = $_FILES["file"]["size"];
	$allowed_file_types = array('.doc','.docx','.rtf','.pdf');
 
	if (in_array($file_ext,$allowed_file_types)  &&  ($filesize < 200000)) {
 
		// rename file
		$newfilename = md5($file_basename) . $file_ext;
 
		if (file_exists("upload/" . $newfilename)) {		
			// file already exists error
			echo "You have already uloaded this file.";			
		} else {		
			move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $newfilename);
			echo "File uploaded successfully.";			
		}
 
	} elseif (empty($file_basename)) {	
		// file selection error
		echo "Please select a file to upload.";		
	} elseif ($filesize > 200000) {	
		// file size error
		echo "The file you are trying to upload is too large.";		
	} else {	
		// file type error
		echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
		unlink($_FILES["file"]["tmp_name"]);		
	}
 
}
 
?>

Having a script like this in your arsenal is a great tool. Developers often need to have a user upload a file back the server, making this script a nice trick in the bag. And if you look closely, it isn’t very complicated. In lines seven through eleven of the PHP, we define some variables that get used in the rest of the script. Pay particular attention to the array called $allowed_file_types. That array determines the types of files a user can upload with this script. You’ll also want to pay attention to line sixteen on the script, which is where we rename the file. I am just md5-ing the file name, but you can use anything you want here.


Comments

  1. Khim Sambo Rothana said on June 21, 2010

    I’m so happy to see your brilliant code. 100% perfectly works. Thank you so much for your contribution.

  2. Khim Sambo Rothana said on August 31, 2010

    Hey, guys!

    I have to change the file size to be less then 4MB (<4194304), but it's not working. Why? I can still upload the bigger size.

    Please help!

    Good luck,
    Rothana

  3. Zac said on September 3, 2010

    I’m not too sure why it isn’t working. Most PHP servers, by default, only put caps on how big a file can be. In the code, this is where I’m putting limits on the file size: $filesize < 200000.

  4. Nux said on October 26, 2010

    what do i name the php file?

  5. Otodeluxe said on October 29, 2010

    Great tutorial! Please do you know how to upload images to db

  6. Zac said on November 10, 2010

    You can name it anything you want, I guess.

  7. Zac said on March 26, 2011

    Yes, you could convert your image into base64 and store the encoded string in a database.

  8. Zac Vineyard’s Blog - Upload a File to a Remote Server with Phonegap said on March 28, 2011

    [...] The above code uses PHP’s move_uploaded_file() to move the uploaded file from a temporary location to a new directory. To make sure it works, change “/srv/www/upload/” to a directory on your server. I usually have to pass an absolute file-path as the second variable in the move_uploaded_file() for it to work. You can learn more about PHP uploads in a previous post of mine. [...]

  9. Ashley said on April 3, 2011

    how would i change this so there is no limit to the file types that are uploaded?

  10. Zac said on April 4, 2011

    Hi Ashley,
    You can just add any file extension you want to the array of extensions called $allowed_file_types. Remember not to allow people to upload PHP files for security.

  11. Mark said on April 12, 2011

    If your intention is to share this with others you should consider rewriting this as a class. This would allow for greater customization since the save path could be specified as can the list of acceptable extensions and file sizes. Also, using php5 anonymous functions you could also pass in a function that can be used to create the new filename.

    Not only would these things make it easier to share with others but it would also make it more useful in your own projects since you would not have to edit this code for every project or for different usages within a project.

  12. Hasan said on June 27, 2011

    thanks very much for this article..
    very help me…
    thanks thanks thanks… :)

  13. Paulius said on July 5, 2011

    Hello. I am very happy that found your script. Thank you very much. But one problem in script are. If(emty($file_basename)) {echo “BlaBlaBla”; } Didin’t work… How to fix it?

  14. Zac said on July 7, 2011

    I think you are misspelling the word empty. Otherwise, your code example looks fine.

  15. Danthe said on July 23, 2011

    Awesome script Zac, thank you very much for this, since im almost starting in php this was very helpful and very well explained. Just a question, in: if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000)) what's the $filesize "200000" units, i mean, are those kb, mb, bytes?
    Thanks in advance

  16. Zac said on July 24, 2011

    Hi Danthe,
    The number expressed in the $filesize variable is in bytes. So that 200000 is 200kb.

  17. Jaime said on September 20, 2011

    How would the code change if I wanted the new file name to be a timestamp?

  18. Zac said on September 20, 2011

    To change the name of the file to a timestamp, you’d modify the $newfilename variable to this:

    $newfilename = time() . $file_ext;

  19. kk said on September 26, 2011

    Hi

    I am trying to upload image from in i phone with the help of api
    And i am getting response array like this

    Array
    (
      [$_FILES] => Array
      (
        [$_FILES] => Array ( [name] => Array ( ['U_PHOTO'] => file )
        [type] => Array ( ['U_PHOTO'] => application/octet-stream )
        [tmp_name] => Array ( ['U_PHOTO'] => /tmp/phpL6b8yh )
        [error] => Array ( ['U_PHOTO'] => 0 )
        [size] => Array ( ['U_PHOTO'] => 32659 )
      )
    
    )
    

    so from this array how can i get filename/imagename.

    please help to find out solution for this

  20. kk said on September 26, 2011

    HI

    sorry i was misprint my response array in my last post.
    actual array was

    Array
    (
        [$_FILES] => Array
        ( 
    
        [name] => Array ( ['U_PHOTO'] => file )
        [type] => Array ( ['U_PHOTO'] => application/octet-stream )
        [tmp_name] => Array ( ['U_PHOTO'] => /tmp/phpL6b8yh )
        [error] => Array ( ['U_PHOTO'] => 0 )
        [size] => Array ( ['U_PHOTO'] => 32659 )
    
        )
    
    )
    
  21. Danthe said on September 28, 2011

    Thanks for your response that helped me a lot =)

  22. Eric said on October 24, 2011

    Awesome post Zac!

    I tried it and it looks like it’s uploading from the phone to the php script, but the Response dialog shows an empty array coming from PHP and the file isn’t uploading.

    When I upload a file from HTML to the same PHP script it gives me all the info about the uploaded file, and the image uploads successfully.

    Am I doing something wrong?

    Testing with a Droid 3.

  23. Andrew said on December 28, 2011

    i am using iis 7 or something similar

    when i try uploading the file i get
    :
    Server Error

    405 – HTTP verb used to access this page is not allowed.
    The page you are looking for cannot be displayed because an invalid method (HTTP verb) was used to attempt access.
    how do i resolve this?

Add Your Comment