A Better PHP Upload and Rename Script
An 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.

I’m so happy to see your brilliant code. 100% perfectly works. Thank you so much for your contribution.
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
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.what do i name the php file?
Great tutorial! Please do you know how to upload images to db
You can name it anything you want, I guess.
Yes, you could convert your image into base64 and store the encoded string in a database.
[...] 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. [...]
how would i change this so there is no limit to the file types that are uploaded?
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.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.
thanks very much for this article..
very help me…
thanks thanks thanks… :)
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?
I think you are misspelling the word empty. Otherwise, your code example looks fine.
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
Hi Danthe,
The number expressed in the
$filesizevariable is in bytes. So that 200000 is 200kb.How would the code change if I wanted the new file name to be a timestamp?
To change the name of the file to a timestamp, you’d modify the $newfilename variable to this:
$newfilename = time() . $file_ext;
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
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 ) ) )Thanks for your response that helped me a lot =)
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.
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?