A Simple File Upload Script using PHP
By Ikki on May 9, 2008 in Tutorials, Web Development
Hi peeps,
Ever found yourself wondering how to create a File Upload System using PHP? Today is your lucky day!
Follow me and I’ll show you how to implement a simple file upload script in your site using PHP.
What we need to get started:
- A Web Server (like XAMPP) or Internet Host with Php capabilities.
- Basic to semi-advanced Php knowledge.
- Basic knowledge of HTML.
- A text editor to create our little script (like notepad).
- A folder in our server where to upload the files (eg. uploads, chmodded 777)
The Form
The first thing we need is the form that will allow our visitors to select an upload their file to our site. Here’s a sample snippet (which you can also download for testing purposes
):
1 2 3 4 5 6 7 8 9 10 11 12 13 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2" />
<title>Rauru.com - Upload Test</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label>File:</label> <input type="file" name="file" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html> |
Let’s take a closer, deeper look to this form. As you can see, it’s just like any form you might have previously seen in other places except that this time we’re adding a special attribute: ENCTYPE. With it, we are telling our visitor’s browser that this form handles files by setting multipart/form-data as it’s value.
Once the user clicks on the Submit button, the form will send all the data via POST to our script, upload.php, which will handle it and save it to our uploads folder (you didn’t forget to create it, did you?)
The Upload Script
Before we get started, there are a few things that we need to know in order to understand what this snippet do. Php has some predefined variables called Super Variables. These include $_GET, $_POST, $_COOKIE, $_SESSION, $_SERVER, $_ENV, $_FILES and $_REQUEST.
$_FILES is an array that will contain all the information of our uploaded file. The contens of $_FILES are saved as follows:
- $_FILES['file']['name']: the original name of the file in the visitor’s computer.
- $_FILES['file']['type']: the mime-type of our file (that is, the file type).
- $_FILES['file']['size']: the size of the uploaded file (in bytes).
- $_FILES['file']['temp_name']: The temporary filename of the file in which the uploaded file was stored on the server.
- $_FILES['file']['error']: The error code associated with this upload.
Note that ‘file‘ is the name we set for our file input field in our upload form. It can be whatever you want! Here’s our script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | <?php // Upload directory: remember to give it write permission! $uploaddir = "upload/"; // what file types do you want to disallow? $blacklist = array(".php", ".phtml", ".php3", ".php4", ".php5", ".exe", ".js",".html", ".htm", ".inc"); // allowed filetypes $allowed_filetypes = array('.jpg','.gif','.bmp','.png'); if (!is_dir($uploaddir)) { die ("Upload directory does not exists."); } if (!is_writable($uploaddir)) { die ("Upload directory is not writable."); } if ($_POST['submit']) { if (isset($_FILES['file'])) { if ($_FILES['file']['error'] != 0) { switch ($_FILES['file']['error']) { case 1: print 'The file is too big.'; // php installation max file size error exit; break; case 2: print 'The file is too big.'; // form max file size error - DEPRECATED exit; break; case 3: print 'Only part of the file was uploaded.'; exit; break; case 4: print 'No file was uploaded.'; exit; break; case 6: print "Missing a temporary folder."; exit; break; case 7: print "Failed to write file to disk"; exit; break; case 8: print "File upload stopped by extension"; exit; break; } } else { foreach ($blacklist as $item) { if (preg_match("/$item\$/i", $_FILES['file']['name'])) { echo "Invalid filetype !"; unset($_FILES['file']['tmp_name']); exit; } } // Get the extension from the filename. $ext = substr($_FILES['file']['name'], strpos($_FILES['file']['name'],'.'), strlen($_FILES['file']['name'])-1); // Check if the filetype is allowed, if not DIE and inform the user. if(!in_array($ext,$allowed_filetypes)){ die('The file you attempted to upload is not allowed.'); } if (!file_exists($uploaddir . $_FILES["file"]["name"])) { // Proceed with file upload if (is_uploaded_file($_FILES['file']['tmp_name'])) { //File was uploaded to the temp dir, continue upload process if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $_FILES['file']['name'])) { // uploaded file was moved and renamed succesfuly. Display a message. echo "Upload successful!"; } else { echo "Error while uploading the file, Please contact the webmaster."; unset($_FILES['file']['tmp_name']); } } else { //File was NOT uploaded to the temp dir switch ($_FILES['file']['error']) { case 1: print 'The file is too big.'; // php installation max file size error break; case 2: print 'The file is too big.'; // form max file size error break; case 3: print 'Only part of the file was uploaded'; break; case 4: print 'No file was uploaded'; break; case 6: print "Missing a temporary folder."; break; case 7: print "Failed to write file to disk"; break; case 8: print "File upload stopped by extension"; break; } } } else { // There's a file with the same name echo "Filename already exists, Please rename the file and retry."; unset($_FILES['file']['tmp_name']); } } } else { // user did not select a file to upload echo "Please select a file to upload."; } } else { // upload button was not pressed header("Location: form.html"); } ?> |
Now, what does our little script do?:
- Set our upload folder.
- Set a fyletype blacklist and a filetype whitelist.
- Check that our uploads directory exists and is writable.
- Now, we validate that our user clicked on the Submit button. If he didn’t then redirect him to the form.
- Check if our super variable $_FILES has found any error on our uploaded file.
- Validate our uploaded file against our file type blacklist to prevent people uploading things that we don’t want on our server.
- Check that the file doesn’t exist. If there’s another file with the same name we alert our visitor and abort the upload process. Otherwise we save the file in our uploads folder and let him know that the upload was succesful.
Hope that helps
P. S.: oh, and if you liked my tutorial please don’t forget to Digg it! ![]()



It’s a nice one, definelty handy specially for php newbies..
Keep going!
- Wakish -
Wakish | May 10, 2008 | Reply
i dont have a website yet.. but its someone who told me to upload something to his website.. so i found dis tutorial is didactic.. good for newbies
rain | May 18, 2008 | Reply
Excelente! muchas gracias!
jose | May 18, 2008 | Reply
@jose: De nada
Ikki | May 19, 2008 | Reply
Do just need to upload the uploads folder, form.php and upload.php on to my site? Because in my browser when i click submit it has just a blank page… What did i do wrong?
Karen | Jul 3, 2008 | Reply
@Karen: You need to create a “upload” folder on your server and give it writing permissions before using this script. Remember to change the path to its location in line 3!
Give it a try and let me know if it worked, ok?
Ikki | Jul 3, 2008 | Reply
Gave ‘upload’ folder writing permissions 0774. Changed the path to ‘public_html/orielchambers/upload’ (the path on my server). The browser sends my page to upload.php with blank page still.
Karen | Jul 4, 2008 | Reply
@Karen: I think you’re setting the wrong path. Try this: put both scripts (the form and the uploaded script) in the folder “orielchambers” and set your $uploaddir variable to “upload/”.
If it doesn’t work please let me know. I may give you a hand with your script if you allow me to do so.
Ikki | Jul 4, 2008 | Reply
No sorry it doesnt work.
Here’s my script:-
<?php
// Upload directory: remember to give it write permission!
$uploaddir = “upload/”;
// what file types do you want to disallow?
$blacklist = array(“.php”, “.phtml”, “.php3?, “.php4?, “.php5?, “.exe”, “.js”,“.html”, “.htm”, “.inc”);
// allowed filetypes
$allowed_filetypes = array(‘.jpg’,‘.gif’,‘.bmp’,‘.png’);
if (!is_dir($uploaddir)) {
die (“Upload directory does not exists.”);
}
if (!is_writable($uploaddir)) {
die (“Upload directory is not writable.”);
}
if ($_POST['submit']) {
if (isset($_FILES['file'])) {
if ($_FILES['file']['error'] != 0) {
switch ($_FILES['file']['error']) {
case 1:
print ‘The file is too big.’; // php installation max file size error
exit;
break;
case 2:
print ‘The file is too big.’; // form max file size error - DEPRECATED
exit;
break;
case 3:
print ‘Only part of the file was uploaded’.;
exit;
break;
case 4:
print ‘No file was uploaded.’;
exit;
break;
case 6:
print “Missing a temporary folder.”;
exit;
break;
case 7:
print “Failed to write file to disk”;
exit;
break;
case 8:
print “File upload stopped by extension”;
exit;
break;
}
} else {
foreach ($blacklist as $item) {
if (preg_match(“/$item\$/i”, $_FILES['file']['name'])) {
echo “Invalid filetype !”;
unset($_FILES['file']['tmp_name']);
exit;
}
}
// Get the extension from the filename.
$ext = substr($_FILES['file']['name'], strpos($_FILES['file']['name'],‘.’), strlen($_FILES['file']['name'])-1);
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes)){
die(‘The file you attempted to upload is not allowed.’);
}
if (!file_exists($uploaddir . $_FILES["file"]["name"])) {
// Proceed with file upload
if (is_uploaded_file($_FILES['file']['tmp_name'])) {
//File was uploaded to the temp dir, continue upload process
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $_FILES['file']['name'])) {
// uploaded file was moved and renamed succesfuly. Display a message.
echo “Upload successful!”;
} else {
echo “Error while uploading the file, Please contact the webmaster.”;
unset($_FILES['file']['tmp_name']);
}
} else {
//File was NOT uploaded to the temp dir
switch ($_FILES['file']['error']) {
case 1:
print ‘The file is too big.’; // php installation max file size error
break;
case 2:
print ‘The file is too big.’; // form max file size error
break;
case 3:
print ‘Only part of the file was uploaded’;
break;
case 4:
print ‘No file was uploaded’;
break;
case 6:
print “Missing a temporary folder.”;
break;
case 7:
print “Failed to write file to disk”;
break;
case 8:
print “File upload stopped by extension”;
break;
}
}
} else { // There’s a file with the same name
echo “Filename already exists, Please rename the file and retry.”;
unset($_FILES['file']['tmp_name']);
}
}
} else { // user did not select a file to upload
echo “Please select a file to upload.”;
}
} else { // upload button was not pressed
header(“Location: form.html”);
}
?>
Karen | Jul 4, 2008 | Reply
Upload.php and form.html and the ‘uploads’ folder are all in orielchambers folder on public.html.
Karen | Jul 4, 2008 | Reply
@Karen: I think I found your problem. See this line in your script:
$blacklist = array(“.php”, “.phtml”, “.php3?, “.php4?, “.php5?, “.exe”, “.js”,“.html”, “.htm”, “.inc”);
You’re missing some closing double-quotes in your blacklist array. It should be like this:
$blacklist = array(“.php”, “.phtml”, “.php3?”, “.php4?”, “.php5?”, “.exe”, “.js”,“.html”, “.htm”, “.inc”);
It should work now. You were getting a blank page because of a PHP error. You should enable PHP to display errors in your scripts in order to let you know when something goes wrong (but use it only on testing enviroments, never on production enviroments!).
Let me know if it worked, ok?
Ikki | Jul 4, 2008 | Reply
Corrected the line, and….. it still gives me a blank page. This one is weird!
Karen | Jul 5, 2008 | Reply
@Karen: Strange. I didn’t find any further errors on your script. Try adding this line to your upload.php:
error_reporting(E_ALL);
This function will tell PHP to display any errors it might encounter while executing this script. Please copy the error message and post it here
Ikki | Jul 5, 2008 | Reply
Still a blank page.
Karen | Jul 6, 2008 | Reply
@Karen: weird. I’m beginning to think that your problem is not your code but your host’s server configuration. Try adding these commands to your .htaccess file in public_html to override any settings from your host and force their server to display PHP errors:
php_flag display_errors on
php_flag display_startup_errors on
php_value error_reporting 2047
You might algo want to try this.
If none of the above works you might want to contact your admin.
Ikki | Jul 6, 2008 | Reply
This brings up an error:-
Parse error: syntax error, unexpected ‘,’ in /data01/hunter/public_html/orielchambers/upload.php on line 5
(This is line 5):-
$blacklist = array(“.php”, “.phtml”, “.php3?”, “.php4?”, “.php5?”, “.exe”, “.js”,“.html”, “.htm”, “.inc”);
Karen | Jul 7, 2008 | Reply
@Karen: haha xD Damn line! Ok my guess is that the formated double-quotes (“ ”) are the ones causing all this mess. Replace line 5 with:
$blacklist = array(”.php”, “.phtml”, “.php3?”, “.php4?”, “.php5?”, “.exe”, “.js”, “.html”, “.htm”, “.inc”);
Ikki | Jul 7, 2008 | Reply
Parse error: parse error, unexpected ‘;’ in /home/content/***/html/upload.php on line 24
Edited by Ikki - Reason: sensitive info in the comment
Seneca | Jul 16, 2008 | Reply
@Seneca: Hi there, mind to share your script with me? It’s hard to tell why are you getting this error without looking at the source code
Ikki | Jul 16, 2008 | Reply
i’m basically trying to make a simple upload form for artists to upload their demo submissions directly to my folder: http://www.audiologicrecordings.com/contact.html
Seneca | Jul 16, 2008 | Reply
@Seneca: Try putting your script into a .zip file, upload it to your host and send me the link so I can check it.
Ikki | Jul 16, 2008 | Reply
http://www.audiologicrecordings.com/upload.php.zip
Seneca | Jul 16, 2008 | Reply
@Seneca: Found the error. Lose the dot (”.”) at the end of line 30, that was the thing causing the problem!
Ikki | Jul 16, 2008 | Reply
Can you implement a category selector for this? or make a tutorial on it so people can select which folder the files will be stored on? thanks
Jd | Jul 23, 2008 | Reply
@Jd: Hi there. I’m sure I can come up with something like that. I’ll give it a try as soon as I get some spare time
Thanks for the idea!
Ikki | Jul 23, 2008 | Reply