Howto: Make a simple files upload system
Howto, php March 23rd, 2008An upload system for files is nowadays considered as a mandotory tool for content management systems (CMS). In this tutorial you will learn how to create a basic file upload system. I’ll start by creating the hardest part of the upload system. The upload form.
The form itself is also different from usual html forms.
<form action="form.php" method="post" name="add-form" enctype="multipart/form-data"> <label for="file">Filename:</label><br /> <input type="file" name="file" id="file" /><br /> <input type="hidden" name="action" value="add" /> <!-- Hidden input type, checking which form to use--> <input type="submit" name="submit" value="Upload" /> </form>
As you can see, the form starts with the action and method. However, the enctype is probably a new attribute you’ve spotted in an HTML form. The enctype attribute indicates how the data is encoded. When an HTML form has no enctype, the default enctype is used, which is “application/x-www-form-urlencoded”. If you run this code you’ll already see a textfield and a browse button next to it. Now for the “form.php”, which is the action the form refers to.
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 | if(isset($_POST['submit'])) { // If action is add. if($_POST['action'] == 'add') { // Define the folder where the file will be uploaded. $upload_path = './uploads/' . $_FILES['file']['name']; // Check if the file already exists in the folder. if(!file_exists($upload_path)) { // Check the size of the file. // The file should be under 100 kb. But OVER 0 bytes. if($_FILES['file']['size'] < 100000 && $_FILES['file']['size'] > 0) { // If there are any errors. if($_FILES['file']['error']) { echo "Error: " . $_FILES['file']['error']; } else { // Success! echo "File successfully uploaded.<br /><br />"; echo "The filename is: <strong>" . $_FILES['file']['name'] . "</strong><br />"; echo "The filesize is: <strong>" . $_FILES['file']['size'] . "</strong><br />"; echo "The filetype is: <strong>" . $_FILES['file']['type'] . "</strong><br />"; echo "The file is temporary saved in: <strong>" . $_FILES['file']['tmp_name'] . "</strong><br />"; // Move uploaded file to upload folder. move_uploaded_file($_FILES['file']['tmp_name'], $upload_path); } } else { echo $_FILES['file']['size'] < 1 ? 'Incorrect filename.' : 'File size is too big'; } } else { echo "File already exists in your folder. "; } } } |
In the code an upload path is given in a variable. You can change the upload path to the destinated folder where to upload the file s into. In this code the file is uploaded in the currentfolder/uploads/. When a file is uploaded the file has the exact same filename as the filename you’ve chosen to upload. So if your file is named ‘hi.html’. The uploaded result resides in ‘currentfolder/uploads/hi.html’.
It’s also possible to filter files. For example, if you only want files to have a limited amount of extensions you could make an array with extensions.
$allowed_extensions = array( 'png', 'gif', 'bmp', 'jpg', 'jpeg' );
To check if a file contains the extension, use the following code.
$filename = $_FILES['file']['name']; $new_filename = explode('.', $filename); if(in_array($new_filename[count($new_filename) -1], $allowed_extensions)) { // Continue with the code } else { // Stop the code. }
From the $_FILES super global, the variable $filename is created. The filename is modified to an array, using the ” . ” as the place to split the variable. So in this case, the filename could be for example; hello.gif. This variable would be split in two values,
// $new_filename array('hello', 'gif');
By checking if the last value is correctly nested in the extensions array, the code should return TRUE. Elsewise the code should turn out FALSE and print the error message, saying that the filename contains an invalid extension.
You now know how to create an upload form and validating the upload form. The next step is how to make the php code to view a directory and how to show all files available in the directory. This file is named ‘view.php’.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | // Specify the uploads folder in a variable. // This is exactly the same folder used in the upload script. $dir = './uploads/'; // Try to open the directory. if($dir = opendir($dir)) { // Create an HTML table using a small CSS style. echo '<table style="width: 250px;">'; // Create the variable $file. If reading the dir DOESN'T turn out FALSE, print out the file with a link. while(($file = readdir($dir)) !== false) { // Remove the dots in $file. if($file != '.' && $file != '..') { echo '<tr>'; // Print a link containing the name of the file. // The link continues to delete.php?file=$filename. // This is used for deleting the uploaded file. echo '<td>' . $file . '</td><td><a href="delete.php?file=' . $file . '">delete</a>'; echo '</tr>'; } } echo '</table>'; // Close the opened directory. closedir($dir); } |
After running this script, you’ll see an 250 pixels width table containing the name of the file and a hyperlink refering to the delete.php page. Now, let’s create the delete page.
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Using the superglobal $_GET, get the filename. $file = $_GET['file']; // The upload dir, exactlty the same as in the previous scripts. $upload_dir = './uploads/'; // The complete file path to the file. $file_path = $upload_dir . $file; // Check if the filepath is correct. if(is_file($file_path)) { // Delete the file using the unlink function. unlink($file_path); // Give a message to tell the user, the file is deleted. echo "File " . $file . " deleted."; } |
This script isn’t very hard, is it? You’ve seen the hyperlink refering to a ‘delete.php’ page. After the delete.php you’ve seen ‘file=$filename’. with the $_GET[’file’] array, the PHP script literally GETS the name after ‘file’. So in this case it’s $filename. $_GET methods are commonly used to make websites more dynamic and it’s much better than creating seperate pages and updating them frequently.
Download the zip file.
March 24th, 2008 at 3:17 pm
Can I save uploads at IP-address? Thanks for the script!
April 20th, 2008 at 11:05 am
What do you mean by save uploads by IP-address?
April 24th, 2008 at 1:16 pm
Hey! Im trying to make a php .txt editor…
Basicly all i want is a textbox and a button that when you click the button it saves the text to a text file. (i dont want it to add it to the text i want it to be the onlything like overwright it)
Hope you can help!
April 26th, 2008 at 10:01 am
This is fantastic and very easy to follow, especially for someone just starting php, like me
Great work!
June 4th, 2008 at 4:13 pm
LJAse7 sd80347yv35t8574dcu0r
June 4th, 2008 at 9:38 pm
UzKrXC fv629ff73asdhlvthi57fvt4
June 5th, 2008 at 9:30 am
pJkV7E fdf043hj93jkfjw845qgtj6fqp
June 17th, 2008 at 6:54 pm
Very helpful. Exactly what I was searching for.
Thank you!
June 22nd, 2008 at 11:36 pm
cpzdbqf sbalvehk qtkfayrd iskocaxf csrhovae jdfcqpiog avnsifgd
June 22nd, 2008 at 11:42 pm
yomr kqvia ubew bznp ekcl xrlyo dsqcfh
June 22nd, 2008 at 11:52 pm
sdji slnt ivyne dcvbta mauwdcby dgwhrscn uvfocqnm
July 5th, 2008 at 11:46 pm
hi nice site thx man
July 6th, 2008 at 7:54 am
good site dude
July 6th, 2008 at 8:15 am
good work man
July 11th, 2008 at 4:10 pm
This was good information. I’ve passed your url to a few of my associates. Take care. RapidInternet Inc.
July 13th, 2008 at 11:04 am
Thanks for the great info. I hope you’ll follow this with some more great content.
July 20th, 2008 at 1:54 am
Hey, I found you in google and glad i did, this is just the topics that I was looking for. Komo
July 20th, 2008 at 9:20 am
Can you tell me how can i put the add and view in same window, in same page, when i upload file i see it in the same window where is option upload. sorry on bad english. THANKS!
July 20th, 2008 at 3:15 pm
Nice post, you got some good points there - thank you.
July 28th, 2008 at 9:13 am
ve8TkY hi! hice site!
July 30th, 2008 at 1:22 pm
Q4bnin hi! hice site!
July 31st, 2008 at 10:38 pm
hi nice site thx
August 6th, 2008 at 8:42 pm
In your opinion, what’s the best movie ever created?
August 6th, 2008 at 8:42 pm
In your opinion, what’s the best movie ever created?
August 14th, 2008 at 11:37 am
I read a simliar post just the other day by Sandra Kosineck but yours is much better.
August 16th, 2008 at 7:05 pm
It covers guitars, amplifiers and related equipment
August 17th, 2008 at 7:02 am
Can someone explain where to insert the code to only allow certain extensions? I’ve tried and it hasn’t worked.
Thanks.
August 17th, 2008 at 1:48 pm
I read a simliar post just the other day by Sandra Kosineck but yours is much better.
August 17th, 2008 at 4:36 pm
funny, Tony Santos wrote about this topic exactly the other day.