I create a lot of websites that allow administrators to upload files to their own website. Since allowing user customization has become more and more important on websites these days, I thought I'd share how easy it is to handle file uploads in PHP.

The XHTML Form

HTML Code:
<form action="accept-file.php" method="post" enctype="multipart/form-data">
	Your Photo: <input type="file" name="photo" size="25" />
	<input type="submit" name="submit" value="Submit" />
</form>
You'll need to use the multipart/form-data value for the form's enctype property. You'll also obviously need at least one input element of the file type. The form's action tag must provide a URL which points the a file containing the piece of PHP below.

The PHP

PHP Code:
//if they DID upload a file...
if($_FILES['photo']['name'])
{
    
//if no errors...
    
if(!$_FILES['photo']['error'])
    {
        
//now is the time to modify the future file name and validate the file
        
$new_file_name strtolower($_FILES['photo']['tmp_name']); //rename file
        
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
        
{
            
$valid_file false;
            
$message 'Oops!  Your file\'s size is to large.';
        }
        
        
//if the file has passed the test
        
if($valid_file)
        {
            
//move it to where we want it to be
            
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
            
$message 'Congratulations!  Your file was accepted.';
        }
    }
    
//if there is an error...
    
else
    {
        
//set that to be the returned message
        
$message 'Ooops!  Your upload triggered the following error:  '.$_FILES['photo']['error'];
    }
}

//you get the following information for each file:
$_FILES['field_name']['name']
$_FILES['field_name']['size']
$_FILES['field_name']['type']
$_FILES['field_name']['tmp_name'
My commenting in the PHP above outlines the way the process works, so I'll just mention a few notes about file uploads in PHP:

Many shared hosting servers allow a very low maximum file upload size. If you plan on accepting larger files, you should consider a dedicated or virtual dedicated server.

To adjust the file upload size in PHP, modify the php.ini file's "upload_max_filesize" value. You can also adjust this value using PHP's .ini_set() function.

The file upload counts towards the hosting environment's $_POST size, so you may need to increase the php.ini file's post_max_size value.

Be sure to do a lot of file validation when allowing users to upload files. How horrible would it be to allow a user to upload a .exe file to your server? They could do horrible things on the server.

View more threads in the same category: