PHP Tutorial - PHP Form File Upload






A file select field allows the users to choose a file on their hard drive for uploading to the server. The value attribute is usually ignored by the browser:

<label for="fileSelectField">A file select field</label> 
<input type="file" name="fileSelectField" id="fileSelectField" value="" /> 

Information

PHP creates a superglobal array called $_FILES containing various pieces of information about the file or files.

Each file is described by an element in the $_FILES array keyed on the name of the field that was used to upload the file.

For example, say your form contained a file select field called photo :

  <input type="file" name="photo" value="" />  

If the user uploaded a file using this field, its details would be accessible via the following PHP array element:

$_FILES["photo"]

This array element is itself an associative array that contains information about the file. For example, you can find out the uploaded file ' s filename like this:

$filename = $_FILES["photo"]["name"];




Fields of file information

Here's a full list of the elements stored in each nested array within the $_FILES array:

Array ElementDescription
nameThe filename of the uploaded file.
typeThe MIME type of the uploaded file. For example, a JPEG image would probably have a MIME type of image/jpeg , whereas a QuickTime movie file would have a MIME type of video/quicktime.
sizeThe size of the uploaded file, in bytes.
tmp_nameThe full path to the temporary file on the server that contains the uploaded file.
errorThe error or status code associated with the file upload.

Error

Error element contains an integer value that corresponds to a built-in constant that explains the error.

Possible values include:

ConstantValueMeaning
UPLOAD_ERR_OK0The file was uploaded successfully.
UPLOAD_ERR_INI_SIZE1The file is bigger than the allowed file size specified in the upload_max_filesize directive in the php.ini file.
UPLOAD_ERR_FORM_SIZE2The file is bigger than the allowed file size specified in the MAX_FILE_SIZE directive in the form.
UPLOAD_ERR_NO_FILE4No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR6PHP doesn ' t have access to a temporary folder on the server to store the file.
UPLOAD_ERR_CANT_WRITE7The file couldn ' t be written to the server ' s hard disk for some reason.
UPLOAD_ERR_EXTENSION8The file upload was stopped by one of the currently loaded PHP extensions.




File Size

PHP allows you to limit the size of uploaded files.

First, you can add or edit a directive called upload_max_filesize in the php.ini file:

; Maximum allowed size for uploaded files. 
upload_max_filesize = 32M   

If a user tries to upload a file larger than this value (32 megabytes in this example), the file upload is cancelled and the corresponding error array element is set to UPLOAD_ERR_INI_SIZE.

Second, you can add a hidden form field called MAX_FILE_SIZE that specifies the maximum allowed size in bytes of an uploaded file. This should be placed before the file upload field:

<input type="hidden" name="MAX_FILE_SIZE" value="10000" />   
<input type="file" name="fileSelectField" id="fileSelectField" value="" />   

If the uploaded file is larger than this figure, the upload is cancelled and the corresponding error array element is set to UPLOAD_ERR_FORM_SIZE.

We can check the size of an uploaded file manually and reject it if it's too large:

if ( $_FILES["photo"]["size"]> 10000 ) die( "File too big!" );

Move an Uploaded File

The uploaded file is automatically stored in a temporary folder on the server. To use the file, you need to move it out of the temporary folder using PHP's move_uploaded_file() function.

move_uploaded_file() function takes two arguments: the path of the file to move, and the path to move it to.

You can determine the existing path of the file using the tmp_name array element of the nested array inside the $_FILES array.

move_uploaded_file() returns true if the file was moved successfully, or false if there was an error (such as the path to the file being incorrect).

Here's an example:

if ( move_uploaded_file( $_FILES["photo"]["tmp_name"], "/home/matt/photos/photo.jpg" ) ) { 
   echo "Your file was successfully uploaded."; 
} else { 
   echo "There was a problem uploading your file - please try again."; 
}     

Example 1

Here is an example HTML form that allows users to select a file for uploading to your server.

<form enctype="multipart/form-data" method="post" action="upload.php">
        Send this file: <input name="userfile" type="file" /><br />
        <input type="submit" value="Send File" />
</form>

We give the new file element the name userfile.

If there are file uploads, PHP puts information in the superglobal $_FILES for each one in the form of an array. If you run var_dump() on $_FILES.

<?PHP
$filename = $_FILES['userfile']['name'];                                                         
$filesize = $_FILES['userfile']['size'];
print "Received $filename  - its size is $filesize";
?>

If you find files over a certain size aren't being uploaded properly, you may need to increase the upload_max_filesize setting in your php.ini file.

Example 2

You can move uploaded files using move_uploaded_file() function.

The first parameter is the name of the uploaded file. This corresponds to $_FILES['userfile']['tmp_name']. The second parameter is the target file path name.

If all goes well, PHP returns true, and the file will be where you expect it.

Here is the whole operation in action:

if (move_uploaded_file($_FILES['userfile']['tmp_name'], "/place/for/file"))
{
       print "Received {$_FILES['userfile']['name']} - its size is {$_FILES['userfile']['size']}";
} else {
       print "Upload failed!";
}

Example 3

The move_uploaded_file() function is the same as the rename() function, plus it checks if the file was just uploaded by the PHP script.

To perform this check yourself, use the is_uploaded_file() function. It returns true if the file was uploaded by the script and false if not.

Here is a simple example:

if (is_uploaded_file($somefile)) {
       copy($somefile, "/var/www/userfiles/$somefile");
}

Example 4

A File Upload Script

       <html> 
         <body> 
       <?php 
        if ( isset( $_POST["sendPhoto"] ) ) { 
         processForm(); 
        } else { 
         displayForm(); 
        } 

        function processForm() { 
         if ( isset( $_FILES["photo"] ) and $_FILES["photo"]["error"] == UPLOAD_ERR_OK ) { 
           if ( $_FILES["photo"]["type"] != "image/jpeg" ) { 
             echo "<p>JPEG photos only, thanks!</p>"; 
           } elseif ( !move_uploaded_file( $_FILES["photo"]["tmp_name"], "photos/" . basename( $_FILES["photo"]["name"] ) ) ) { 
             echo "<p>Sorry, there was a problem uploading that photo.</p>" . $_FILES["photo"]["error"] ; 
           } else { 
             displayThanks(); 
           } 
         } else { 
           switch( $_FILES["photo"]["error"] ) { 
             case UPLOAD_ERR_INI_SIZE: 
               $message = "The photo is larger than the server allows."; 
               break; 
             case UPLOAD_ERR_FORM_SIZE: 
               $message = "The photo is larger than the script allows."; 
               break; 
             case UPLOAD_ERR_NO_FILE: 
               $message = "No file was uploaded. Make sure you choose a file to upload."; 
               break; 
             default: 
               $message = "Please contact your server administrator for help."; 
           } 
           echo "<p>Sorry, there was a problem uploading that photo. $message</p>"; 
      } 
     } 

     function displayForm() { 
     ?> 
        <p>Please enter your name and choose a photo to upload, then click  
     Send Photo.</p> 

        <form action="photo_upload.php" method="post" enctype="multipart/form-data"> 
            <input type="hidden" name="MAX_FILE_SIZE" value="50000" /> 

            <label for="visitorName">Your name</label> 
            <input type="text" name="visitorName" id="visitorName" value="" /> 

            <label for="photo">Your photo</label> 
            <input type="file" name="photo" id="photo" value="" /> 

            <input type="submit" name="sendPhoto" value="Send Photo" /> 
        </form> 
     <?php 
     } 

     function displayThanks() { 
     ?> 
        <p>Thanks for uploading your photo
            <?php if ( $_POST["visitorName"] ) echo ", " . $_POST["visitorName"] ?>!
         </p> 
        <p>Here's your photo:</p> 
        <p><img src="photos/<?php echo $_FILES["photo"]["name"] ?>" alt="Photo"/></p> 
     <?php 
     } 
     ?> 

      </body> 
     </html>