PHP - Accessing Information on Uploaded Files

Introduction

Once the form data hits the server, the PHP engine recognizes that the form contains an uploaded file or files, and 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.

Suppose 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" ];

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

Array Element
name
Description
The filename of the uploaded file.
type
The 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.
size
The size of the uploaded file, in bytes.
tmp_name
The full path to the temporary file on the server that contains the uploaded file.
error
The error or status code associated with the file upload.

The error element contains an integer value that corresponds to a built-in constant that explains the status of the uploaded file.

Possible values include:

ConstantValue Meaning
UPLOAD_ERR_OK 0 The file was uploaded successfully.
UPLOAD_ERR_INI_SIZE 1The file is bigger than the allowed file size specified in the upload_max_filesize directive in the php.ini file.
UPLOAD_ERR_FORM_SIZE 2The 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_DIR 6PHP doesn't have access to a temporary folder on the server to store the file.
UPLOAD_ERR_CANT_WRITE7 The file couldn't be written to the server's hard disk for some reason.
UPLOAD_ERR_EXTENSION 8The file upload was stopped by one of the currently loaded PHP extensions.

Related Topic