Upload error handling
Learn to read $_FILES['file']['error'] codes and give meaningful error messages.
Upload error codes
Every upload carries an error code. This code lives in $_FILES['avatar']['error']. If the code is 0 (UPLOAD_ERR_OK) the upload succeeded; any other value means a problem.
Knowing the codes helps you show the right message. For example, 'file too large' and 'no file sent' are different situations that need different messages.
PHP defines these codes as UPLOAD_ERR_* constants. Using the constants (e.g. UPLOAD_ERR_OK instead of 0) makes the code more readable.
Common constants
The most common error constants are:
UPLOAD_ERR_OK(0): no error, upload succeededUPLOAD_ERR_INI_SIZE(1):upload_max_filesizeexceededUPLOAD_ERR_PARTIAL(3): file was only partially uploadedUPLOAD_ERR_NO_FILE(4): no file was selected
You translate these to messages with a match or an array. For example $messages = [UPLOAD_ERR_OK => 'No error', ...]. Then read with $messages[$code] ?? 'Unknown'; this gives each code a clear explanation.
Exercise The errorMessage function
Write an errorMessage(int $code): string function. Inside it, define the $messages array keyed by UPLOAD_ERR_OK, UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_PARTIAL and UPLOAD_ERR_NO_FILE (values: 'No error', 'ini size limit exceeded', 'Partial upload', 'No file'). Then return $messages[$code] ?? 'Unknown: ' . $code. Finally call echo errorMessage(...) . "\n" for UPLOAD_ERR_OK, UPLOAD_ERR_INI_SIZE and UPLOAD_ERR_NO_FILE.
Show example solution
' + code. Echo three codes in order.
Example solution:
<?php
// Build message from error code
function errorMessage(int $code): string {
$messages = [
UPLOAD_ERR_OK => "No error",
UPLOAD_ERR_INI_SIZE => "ini size limit exceeded",
UPLOAD_ERR_PARTIAL => "Partial upload",
UPLOAD_ERR_NO_FILE => "No file",
];
return $messages[$code] ?? "Unknown: " . $code;
}
echo errorMessage(UPLOAD_ERR_OK) . "\n";
echo errorMessage(UPLOAD_ERR_INI_SIZE) . "\n";
echo errorMessage(UPLOAD_ERR_NO_FILE) . "\n";
Test yourself
-
Match constants and meanings
- UPLOAD_ERR_OK
- No error
- UPLOAD_ERR_INI_SIZE
- ini limit exceeded
- UPLOAD_ERR_PARTIAL
- Partial upload
- UPLOAD_ERR_NO_FILE
- No file sent
-
Which constant means a successful upload?
- UPLOAD_ERR_INI_SIZE
- UPLOAD_ERR_OK
- UPLOAD_ERR_PARTIAL
- UPLOAD_ERR_NO_FILE
Show answer
UPLOAD_ERR_OK — Correct. UPLOAD_ERR_OK means no error.
-
Success check
if ($file['error'] === ____) { return 'OK'; }Show answer
if ($file['error'] === UPLOAD_ERR_OK) { return 'OK'; }