File Uploads in PHP

Here is some code which will upload a file to your webserver, the html form is as follows, the "multipart/form-data" bit is important and this will not work without it.

<form action="#" method="post" enctype="multipart/form-data">
<input type="file" name="fileupload">
<input type="text" name="filename">
</form>

The PHP code, to receive the document must go in the header of wherever you've decided to post the form to. The variable $dir must be set to wherever you intend to copy the uploaded file to.

The form posts the file, called here 'fileupload'. PHP will therefor have the following varilables available to it: $fileupload, $fileupload_name, $fileupload_type and $fileupload_size.

Note that the html form offers the option to post a filename, if this is not specified in the form, a the php code will use it's existing name, but transformed to lower case, and with any potentially dodgy characters replaced with underscores.

if($fileupload&&$fileupload_size>0) 
{
$dir="/yourdocuments/public_html/documents/"; 
if (!$filename)
{
$filename=ereg_replace("[^a-z0-9.]+","_",strtolower($fileupload_name)); 
}
if (copy($fileupload, $dir.$filename)) 
{ 
// add success messages and processes here.
} 
unlink($fileupload); 
}

If this is failing to work, and you don't have any of the usual mistakes, the first place to start looking is at the file permissions on the directory you're uploading to.