GetDotted Domains

Viewing Thread:
"A Simple File Uploader with PHP"

The "Freeola Customer Forum" forum, which includes Retro Game Reviews, has been archived and is now read-only. You cannot post here or create a new thread or review on this forum.

Thu 25/06/09 at 18:33
Regular
"previously phuzzy."
Posts: 3,487
A Simple File Uploader with PHP

I remember when I first started creating websites how difficult forms were to put together. Admittedly I was a not-so-bright 12 year old, but back then it was giving me real grief even to put a simple data form together. Now of course it's second nature - apart from file uploads. For some reason there's always a 'gotcha' or a catch before I can get these to work. So, I'm putting together this tutorial for anyone else who suffers this web affliction

=================

The aim

To create a simple file uploader using PHP

- Uploads files from any computer to your website
- OPTIONAL - Keeps a log file of all uploads

=================

The pre-requisites

- A website and a host that supports PHP
- Basic knowledge of HTML

=================

The THINGS TO NOTE: PLEASE READ

- Leaving a file uploader open on your website is pretty risky, so I would strongly recommend placing it in a password protected folder that only selected people can access. Check out my .htaccess tutorial for more information.

- This is NOT an HTML tutorial, or a CSS tutorial. However, these forms will all work inside tables, divs or whatever other containers you want to use. Just make sure every form field is between some type of <form> ...... </form> tags. You can get full HTML and CSS tutorials and reference guides at W3Schools

=================

The steps

My simple uploader has 2 pages :

- Page 1 takes in the relevant details about the upload, and the upload itself
- Page 2 processes the upload information

=================

Step 1 - creating the form

- Create a new webpage with the file extension '.php' (instead of '.html', '.css', '.htm' etc)

- Now you have a choice. Use 1 of the following code snippets where you want your form to appear:

--- Code Snippet 1 is just a basic form, with the file upload form field and a submit button, as well as a 'max file size' field

--- Code Snippet 2 is a more advanced version, with form fields to describe the upload and give it a title. This information can be used in a log file.

Note: I've called my first page 'Upload1.php'

=================

CODE SNIPPET 1 - Minimal basic code for Upload1.php

<form enctype="multipart/form-data" action="upload2.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input name="uploadedfile" type="file" size="50"/>
<input type="submit" class='button' value="Upload File" />
</form>


Let's take a walk through this code to see what it does. For each line, I'll say whether you need to EDIT, or just COPY from me:

EDIT: Line 1 tells the browser that a form is coming up, and that it's going to have an 'upload' field (<form enctype="multipart/form-data".....>). It also tells the browser where to send the form data to (in the code this is called the 'action') - in my case, the file is called 'upload2.php'. Finally, it declares how to send the data. There are 2 main methods: 'GET' sends it as part of the URL, whereas 'POST' sends it hidden as a packet between 2 pages. Because we're sending a file, 'POST' is the best option.

EDIT: Line 2 is a 'hidden' form field that tells the next page what the maximum file size is. I've decided on 1000000 bytes (roughly 10Mb) - you can change this to whatever you want by editing the value="1000000" field.

EDIT or COPY: Line 3 is the file upload form field. You can make the 'input name' whatever you want, along with the size of the field. You don't need to really change much here.

EDIT or COPY: Line 4 is simply the submit button to send the data for processing. You can change the 'value' attribute to whatever you want your button to say. For me, I think 'Upload File' is the best ļ

COPY: Line 5 closes the form.

=================

CODE SNIPPET 2 - Fancy code for Upload1log.php

For this fancy example, I'm using the same basic code above along with some extra form fields. We'll use these to add information into the log files. If you know what you're doing with HTML, feel free to add as many extra fields as you like!

<form enctype="multipart/form-data" action="upload2.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input name="uploadtitle" type="text" size="40" maxlength="35" />
<textarea name="uploaddescription" cols="135" rows="5"></textarea>
<input name="uploadedfile" type="file" size="50"/>
<input type="submit" class='button' value="Upload File" />
</form>


Again, let's go through this. Lines 1, 2, 5, 6 and 7 are the same as Snippet 1. The only new lines are:

EDIT or COPY: Line 4 - this adds a title field to the form so users can give the file a name. Note that I've limited the size of the title to 35 characters ('maxlength') and the size of the input box to 40 characters ('size').

EDIT or COPY: Line 5 adds a text area to provide a description of the upload. I've made mines 135 columns wide, and 5 rows deep.

Feel free to add to or omit this information.

Handy tip - this will only display the form fields, i.e. there will be no information saying what the fields are for. I would recommend putting this form inside a table, then giving everything titles in the table so it makes sense. Something like:

<table><tr><td>Upload Title</td><td> <input name="uploadtitle" type="text" size="40" maxlength="35" /></td></tr></table>

This will create a table with 1 row, and 2 columns. In the first column will be the words 'Upload Title'. In the 2nd will be the upload title form field. I've done this in my real life example at the bottom of the article.

Once you've created your form, you need another page to deal with the data.

=================

Step 2 - dealing with the form data

- You'll need another '.php' page. This time, I've called it 'upload2.php'. Make sure to give it the same name as the 'action' attribute of your form above! This page will:

-- Take the form data from 'upload1.php'
-- Send the file to wherever you want it to go
-- OPTIONAL: log the details in a text file

- This is where the PHP comes in. Again, I've got a basic code snippet and a 'fancy' 1. Depending on which you used before, make the same choice again...

=================

CODE SNIPPET 1 - Minimal basic code for Upload2.php

Please note: Due to Freeola's restrictions on line size, I've had to break up lines 8 & 10 with a SPACE. Please remove this if you copy the code.

<?php
if ($_FILES['uploadedfile']['size'] > 10000000)
{
echo "Error: File size is over limit. Contact admin";
}
else
{
$target_path = $_SERVER['DOCUMENT_ROOT'] SPACE .'/examples/uploads/';
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file SPACE ($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded.";
}
}
?>


Again, let's take a look at the code line by line. For each line, I'll say whether you need to EDIT, or just COPY from me:

COPY: Line 1 tells the browser that some PHP code is coming up.

COPY: Line 2 is a check to make sure that the file you've uploaded isn't over the max size you set before. If it is, lines 3, 4 and 5 print out a message saying the file is too big.

COPY: Lines 6 and 7 are just syntax for PHP.

EDIT: Line 8 is the only line you'll need to edit - the 2nd part in apostrophes is the folder that you want your uploads to go into. For me, I've put ¡§/examples/uploads/". You can put whatever you like - just make sure to put a backslash at the end.

COPY: Line 9 takes the folder you just selected, chucks on the filename to the end, and will be used in the next line.

COPY: Line 10 is the actual function that takes your file, takes where you want to put it, and moves it. You'll notice that the file variable name is ['tmp_name'] and not ['name'] - this is because the form has stored it in a location with a temporary name. If you don't choose a place to move it, then when you change page it would be lost.

COPY: Line 11 outputs a nice message saying that the file upload has been successful, whilst Lines 12 - 14 are just some more PHP syntax.

Now, if you used the 'basic' code from before, and the 'basic' code here, you effectively have an uploader set up now. Congratulations!

================
Code in action:
================

You can check out this code in action here (Synae.co.uk, my site). Please note that I've wrapped the form on upload1.php in a table just for to make it look nicer. You can view the page source code to see exactly what I've done. To view any files you upload in this test, simply navigate to 'http://www.synae.co.uk/examples/uploads/', replacing '' with the file name of the file you've uploaded.

=================

CODE SNIPPET 2- Fancy code for Upload2log.php

So what if you want to log the files that get uploaded? Fair enough. Let's use a log file as well.

Please note: Due to Freeola's restrictions on line size, I've had to break up lines 8 & 10 with a SPACE. Please remove this if you copy the code.

<?php
if ($_FILES['uploadedfile']['size'] > 10000000)
{
echo "Error: File size is over limit. Contact admin";
}
else
{
$target_path = $_SERVER['DOCUMENT_ROOT'] SPACE .'/examples/uploads/';
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file SPACE ($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded.";
$file = "uploads/log.txt";
$fh = fopen($file, 'a');
$stringData = "n".date(r)." ".$_FILES['uploadedfile']['name']." ".$_POST['uploadtitle']." ".$_POST['uploaddescription']." ".$_FILES['uploadedfile']['size']." bytes ".$_SERVER['REMOTE_ADDR']."nr";
fwrite($fh, $stringData);
fclose($fh); }
}
?>


Once more, let's go through the code.

EDIT / COPY: Lines 1 - 11 are exactly the same as before - follow the previous 'basic' instructions here.

EDIT: Line 12 is where the log file should be kept. I've put it in the folder with all the other uploads, and called it log.txt. You don't need to actually create this file - the first upload you do will automatically generate it.

COPY: Line 13 is telling PHP to open the file, and set the mode to 'write'.

EDIT / COPY: Line 14 is putting together a big string of information to write into the file. In my example, I write in the date, the file name, the file title (entered previously), the file description (entered previously), the file size and the IP address that made the upload. ONLY CHANGE THIS if you know what you're doing ;)

COPY: Line 15 writes the information to the file.

COPY: Line 16 closes the file, while lines 17 and 18 are just some more PHP syntax.

Now, if you used the 'fancy' code from before, and the 'fancy' code here, you effectively have an uploader set up that also logs every upload. Congratulations!

================
Code in action:
================

You can check out this code in action here (Synae.co.uk, my site). Please note that I've wrapped the form on upload1log.php in a table just for to make it look nicer. You can view the page source code to see exactly what I've done.

- To view any files you upload in this test, simply navigate to 'http://www.synae.co.uk/examples/uploads/', replacing '' with the file name of the file you've uploaded.

- To view the log file, go to http://www.synae.co.uk/examples/uploads/log.txt.

=================

In summary...

- First off, be aware of the dangers of public uploaders - if anyone can access it, then anyone can upload anything they want. The file size limit is a very basic validation check. If you'd like more info on this aspect of the tutorial just post in the comments.

- To make an uploader with no logging, use the 2 'basic' file examples, demonstrated here.

- To make an uploader with logging, use the 2 'fancy' file examples, demonstrated here.

- If you've got any questions, or come across any weird errors, or have a correction to make - please say in the thread below!

Cheers,

Phuzzy
Fri 26/06/09 at 16:34
Regular
"previously phuzzy."
Posts: 3,487
Thanks for the post Garin :)

Obviously there's a few ways you can set the path - concatenating ['DOCUMENT_ROOT'] to the file name is just one of them.

Would agree that content filtering is key, however for example I use a similar piece of code in a ring-fenced section of my site for staff. Every system has to have an element of trust, mines being that those users that I grant access to such a form on my site, won't abuse it.

When it comes to writing technical posts (particularly ones with 'simple' in the title) it can be a difficult balance between providing too little information and not taking enough precaution (dangerous) or providing too much information and mollycoddling (overwhelming). Much like a previous article I wrote around .htaccess there's always got to be security requirements to consider, but I hope this still gives a little insight into how form uploads work.

EDIT: Interestingly enough, this reminded me of a glitch I got uploading my post the other night - check out this screenshot for some Freeola form-verification fail :)

Screenshot here
Fri 26/06/09 at 15:27
Regular
"Devil in disguise"
Posts: 3,151
You shouldnt use $_SERVER['DOCUMENT_ROOT'] as its unreliable. It certainly isnt set as you'd expect on some freeola servers.

And an upload script that lacks any kind of content filtering is just asking for trouble no matter how access to it is restricted. eg

http://www.synae.co.uk/examples/uploads/hmmm.php
Thu 25/06/09 at 18:33
Regular
"previously phuzzy."
Posts: 3,487
A Simple File Uploader with PHP

I remember when I first started creating websites how difficult forms were to put together. Admittedly I was a not-so-bright 12 year old, but back then it was giving me real grief even to put a simple data form together. Now of course it's second nature - apart from file uploads. For some reason there's always a 'gotcha' or a catch before I can get these to work. So, I'm putting together this tutorial for anyone else who suffers this web affliction

=================

The aim

To create a simple file uploader using PHP

- Uploads files from any computer to your website
- OPTIONAL - Keeps a log file of all uploads

=================

The pre-requisites

- A website and a host that supports PHP
- Basic knowledge of HTML

=================

The THINGS TO NOTE: PLEASE READ

- Leaving a file uploader open on your website is pretty risky, so I would strongly recommend placing it in a password protected folder that only selected people can access. Check out my .htaccess tutorial for more information.

- This is NOT an HTML tutorial, or a CSS tutorial. However, these forms will all work inside tables, divs or whatever other containers you want to use. Just make sure every form field is between some type of <form> ...... </form> tags. You can get full HTML and CSS tutorials and reference guides at W3Schools

=================

The steps

My simple uploader has 2 pages :

- Page 1 takes in the relevant details about the upload, and the upload itself
- Page 2 processes the upload information

=================

Step 1 - creating the form

- Create a new webpage with the file extension '.php' (instead of '.html', '.css', '.htm' etc)

- Now you have a choice. Use 1 of the following code snippets where you want your form to appear:

--- Code Snippet 1 is just a basic form, with the file upload form field and a submit button, as well as a 'max file size' field

--- Code Snippet 2 is a more advanced version, with form fields to describe the upload and give it a title. This information can be used in a log file.

Note: I've called my first page 'Upload1.php'

=================

CODE SNIPPET 1 - Minimal basic code for Upload1.php

<form enctype="multipart/form-data" action="upload2.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input name="uploadedfile" type="file" size="50"/>
<input type="submit" class='button' value="Upload File" />
</form>


Let's take a walk through this code to see what it does. For each line, I'll say whether you need to EDIT, or just COPY from me:

EDIT: Line 1 tells the browser that a form is coming up, and that it's going to have an 'upload' field (<form enctype="multipart/form-data".....>). It also tells the browser where to send the form data to (in the code this is called the 'action') - in my case, the file is called 'upload2.php'. Finally, it declares how to send the data. There are 2 main methods: 'GET' sends it as part of the URL, whereas 'POST' sends it hidden as a packet between 2 pages. Because we're sending a file, 'POST' is the best option.

EDIT: Line 2 is a 'hidden' form field that tells the next page what the maximum file size is. I've decided on 1000000 bytes (roughly 10Mb) - you can change this to whatever you want by editing the value="1000000" field.

EDIT or COPY: Line 3 is the file upload form field. You can make the 'input name' whatever you want, along with the size of the field. You don't need to really change much here.

EDIT or COPY: Line 4 is simply the submit button to send the data for processing. You can change the 'value' attribute to whatever you want your button to say. For me, I think 'Upload File' is the best ļ

COPY: Line 5 closes the form.

=================

CODE SNIPPET 2 - Fancy code for Upload1log.php

For this fancy example, I'm using the same basic code above along with some extra form fields. We'll use these to add information into the log files. If you know what you're doing with HTML, feel free to add as many extra fields as you like!

<form enctype="multipart/form-data" action="upload2.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input name="uploadtitle" type="text" size="40" maxlength="35" />
<textarea name="uploaddescription" cols="135" rows="5"></textarea>
<input name="uploadedfile" type="file" size="50"/>
<input type="submit" class='button' value="Upload File" />
</form>


Again, let's go through this. Lines 1, 2, 5, 6 and 7 are the same as Snippet 1. The only new lines are:

EDIT or COPY: Line 4 - this adds a title field to the form so users can give the file a name. Note that I've limited the size of the title to 35 characters ('maxlength') and the size of the input box to 40 characters ('size').

EDIT or COPY: Line 5 adds a text area to provide a description of the upload. I've made mines 135 columns wide, and 5 rows deep.

Feel free to add to or omit this information.

Handy tip - this will only display the form fields, i.e. there will be no information saying what the fields are for. I would recommend putting this form inside a table, then giving everything titles in the table so it makes sense. Something like:

<table><tr><td>Upload Title</td><td> <input name="uploadtitle" type="text" size="40" maxlength="35" /></td></tr></table>

This will create a table with 1 row, and 2 columns. In the first column will be the words 'Upload Title'. In the 2nd will be the upload title form field. I've done this in my real life example at the bottom of the article.

Once you've created your form, you need another page to deal with the data.

=================

Step 2 - dealing with the form data

- You'll need another '.php' page. This time, I've called it 'upload2.php'. Make sure to give it the same name as the 'action' attribute of your form above! This page will:

-- Take the form data from 'upload1.php'
-- Send the file to wherever you want it to go
-- OPTIONAL: log the details in a text file

- This is where the PHP comes in. Again, I've got a basic code snippet and a 'fancy' 1. Depending on which you used before, make the same choice again...

=================

CODE SNIPPET 1 - Minimal basic code for Upload2.php

Please note: Due to Freeola's restrictions on line size, I've had to break up lines 8 & 10 with a SPACE. Please remove this if you copy the code.

<?php
if ($_FILES['uploadedfile']['size'] > 10000000)
{
echo "Error: File size is over limit. Contact admin";
}
else
{
$target_path = $_SERVER['DOCUMENT_ROOT'] SPACE .'/examples/uploads/';
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file SPACE ($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded.";
}
}
?>


Again, let's take a look at the code line by line. For each line, I'll say whether you need to EDIT, or just COPY from me:

COPY: Line 1 tells the browser that some PHP code is coming up.

COPY: Line 2 is a check to make sure that the file you've uploaded isn't over the max size you set before. If it is, lines 3, 4 and 5 print out a message saying the file is too big.

COPY: Lines 6 and 7 are just syntax for PHP.

EDIT: Line 8 is the only line you'll need to edit - the 2nd part in apostrophes is the folder that you want your uploads to go into. For me, I've put ¡§/examples/uploads/". You can put whatever you like - just make sure to put a backslash at the end.

COPY: Line 9 takes the folder you just selected, chucks on the filename to the end, and will be used in the next line.

COPY: Line 10 is the actual function that takes your file, takes where you want to put it, and moves it. You'll notice that the file variable name is ['tmp_name'] and not ['name'] - this is because the form has stored it in a location with a temporary name. If you don't choose a place to move it, then when you change page it would be lost.

COPY: Line 11 outputs a nice message saying that the file upload has been successful, whilst Lines 12 - 14 are just some more PHP syntax.

Now, if you used the 'basic' code from before, and the 'basic' code here, you effectively have an uploader set up now. Congratulations!

================
Code in action:
================

You can check out this code in action here (Synae.co.uk, my site). Please note that I've wrapped the form on upload1.php in a table just for to make it look nicer. You can view the page source code to see exactly what I've done. To view any files you upload in this test, simply navigate to 'http://www.synae.co.uk/examples/uploads/', replacing '' with the file name of the file you've uploaded.

=================

CODE SNIPPET 2- Fancy code for Upload2log.php

So what if you want to log the files that get uploaded? Fair enough. Let's use a log file as well.

Please note: Due to Freeola's restrictions on line size, I've had to break up lines 8 & 10 with a SPACE. Please remove this if you copy the code.

<?php
if ($_FILES['uploadedfile']['size'] > 10000000)
{
echo "Error: File size is over limit. Contact admin";
}
else
{
$target_path = $_SERVER['DOCUMENT_ROOT'] SPACE .'/examples/uploads/';
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file SPACE ($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded.";
$file = "uploads/log.txt";
$fh = fopen($file, 'a');
$stringData = "n".date(r)." ".$_FILES['uploadedfile']['name']." ".$_POST['uploadtitle']." ".$_POST['uploaddescription']." ".$_FILES['uploadedfile']['size']." bytes ".$_SERVER['REMOTE_ADDR']."nr";
fwrite($fh, $stringData);
fclose($fh); }
}
?>


Once more, let's go through the code.

EDIT / COPY: Lines 1 - 11 are exactly the same as before - follow the previous 'basic' instructions here.

EDIT: Line 12 is where the log file should be kept. I've put it in the folder with all the other uploads, and called it log.txt. You don't need to actually create this file - the first upload you do will automatically generate it.

COPY: Line 13 is telling PHP to open the file, and set the mode to 'write'.

EDIT / COPY: Line 14 is putting together a big string of information to write into the file. In my example, I write in the date, the file name, the file title (entered previously), the file description (entered previously), the file size and the IP address that made the upload. ONLY CHANGE THIS if you know what you're doing ;)

COPY: Line 15 writes the information to the file.

COPY: Line 16 closes the file, while lines 17 and 18 are just some more PHP syntax.

Now, if you used the 'fancy' code from before, and the 'fancy' code here, you effectively have an uploader set up that also logs every upload. Congratulations!

================
Code in action:
================

You can check out this code in action here (Synae.co.uk, my site). Please note that I've wrapped the form on upload1log.php in a table just for to make it look nicer. You can view the page source code to see exactly what I've done.

- To view any files you upload in this test, simply navigate to 'http://www.synae.co.uk/examples/uploads/', replacing '' with the file name of the file you've uploaded.

- To view the log file, go to http://www.synae.co.uk/examples/uploads/log.txt.

=================

In summary...

- First off, be aware of the dangers of public uploaders - if anyone can access it, then anyone can upload anything they want. The file size limit is a very basic validation check. If you'd like more info on this aspect of the tutorial just post in the comments.

- To make an uploader with no logging, use the 2 'basic' file examples, demonstrated here.

- To make an uploader with logging, use the 2 'fancy' file examples, demonstrated here.

- If you've got any questions, or come across any weird errors, or have a correction to make - please say in the thread below!

Cheers,

Phuzzy

Freeola & GetDotted are rated 5 Stars

Check out some of our customer reviews below:

Great services and friendly support
I have been a subscriber to your service for more than 9 yrs. I have got at least 12 other people to sign up to Freeola. This is due to the great services offered and the responsive friendly support.
Thank you very much for your help!
Top service for free - excellent - thank you very much for your help.

View More Reviews

Need some help? Give us a call on 01376 55 60 60

Go to Support Centre
Feedback Close Feedback

It appears you are using an old browser, as such, some parts of the Freeola and Getdotted site will not work as intended. Using the latest version of your browser, or another browser such as Google Chrome, Mozilla Firefox, or Opera will provide a better, safer browsing experience for you.