Very simple upload form

Learning how to create a very simple upload form is very simple.

Lets get started, here is our html so we can put this in say upload.html.

CODE
<form enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="512000" />
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>



The above is pretty self explanitory*. If you dont know what the above it, please go read an html manual.
Okay, the max filesize above is 512000, you may change this to whatever.

Next lets create the php file upload.php


CODE
<?php
$upload_dir 
'/home/www/user/uploads/';  // You will need to set this.
$upload_file $upload_dir basename($_FILES['userfile']['name']);

echo 
"<p>";

if (
move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_file)) {
  echo 
"File is valid, and was successfully uploaded.n";
} else {
   echo 
"Upload failed";
}

echo 
"</p>";
echo 
'<pre>';
echo 
'Here is some more debugging info:';
print_r($_FILES);
print 
"</pre>";

?>



Lets break this down...

First off you need to set your uploads directory, this is where all of the upload will go when uploaded.

CODE
$uploaddir = '/home/www/user/uploads/';  



Now the next part is tricky.


CODE
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);


This takes the file, gives it a temp name inside the upload directory, while it uploads.

This will only be a temp name until the WHOLE file is uploaded!


Next is the if:

CODE
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_file)) {
  echo "File is valid, and was successfully uploaded.n";
} else {
   echo "Upload failed";
}



This checks to see if the file was uploaded successfully or not. If it is or not it will display weather it is or not.


This part just displays what is in the directory and whatnot (outputting an array of files). You may customize it to your wants & needs.


CODE
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";



Hope that helps some people wanting to make an upload form. I think in a bit, I'll add an tutorial on how to create an advanced upload form.

Thursday August 16, 2007 - 2763 reads