The document discusses file uploading in PHP. It explains how to set up an HTML form to allow file uploads with enctype="multipart/form-data" and how to access the uploaded file data with the $_FILES array. It then describes processing the uploaded file by checking for errors, validating the file type, and moving it to a destination folder on the server.
2. HTTP File Upload (RFC 1867)
<form action="file_upload.php" method="post"
enctype="multipart/form-data">
“No characters are encoded. This value is required when you are using
forms that have a file upload control”
<input type="hidden" name="MAX_FILE_SIZE"
value="30000" />
<input type="file" name="upload" />
<input type="submit" value="Upload" />
</form>
• Set attribute METHOD="POST"
• Set attribute ENCTYPE="multipart/form-data"
• Use INPUT element with TYPE="file" to create a file upload control (one
control per file)
• Hidden input field MAX_FILE_SIZE recommends to the web client the limit
of the size of the uploaded file.
3. The $_FILES Array
Index Meaning
name The original name of the file (as it was on the
user's computer).
type The MIME type of the file, as provided by the
browser.
size The size of the uploaded file in bytes.
tmp_name The temporary filename of the uploaded file
as it was stored on the server.
error The error code associated with any problem.
4. Processing the uploaded
items
// "upload" is the name assigned to the input element, as in
// <input type="file" name="upload" />
if (isset($_FILES['upload'])) {
if ($_FILES['upload']['error'] > 0)) {
// File upload fails. See next slide for detailed info about the
// meaning of the error code.
}
else {
// e.g., only allows JPEG image files to be uploaded
// Note: This is not a complete list of MIME types for JPEG images
$allowed = array('image/jpeg', 'image/jpg');
// Continue next page …
5. Processing the uploaded items
if (in_array($_FILES['upload']['type'], $allowed))
{
$tmp = $_FILES['upload']['tmp_name'];
$dst = "C:/uploads/{$_FILES['upload']['name']}";
if (move_upload_file($tmp, $dst)) {
// Success !
}
}
} // End of else
}
6. Error Messages Explained
UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.
UPLOAD_ERR_INI_SIZE
Value: 1; The uploaded file exceeds the upload_max_filesize directive in
php.ini.
UPLOAD_ERR_FORM_SIZE
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was
specified in the HTML form.
UPLOAD_ERR_PARTIAL
Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE
Value: 4; No file was uploaded.