File Uploads with Slim Framework and PHP
Overview
Section titled “Overview”File uploads allow users to submit documents, images, and other files to your server via HTTP POST requests. Slim Framework provides access to uploaded files through the PSR-7 Request object.
HTML Upload Form
Section titled “HTML Upload Form”Required Form Attributes
Section titled “Required Form Attributes”method="POST": file uploads must use POST.enctype="multipart/form-data": without it, the browser sends only the filename, not the file’s content.<input type="file">: creates the file selection control.- The input’s
nameattribute: the key used to read the file on the server.
Example
Section titled “Example”<form action="/upload" method="POST" enctype="multipart/form-data"> <label for="userfile">Select a file:</label> <input type="file" name="userfile" id="userfile"> <input type="submit" value="Upload"></form>The accept attribute (for example, accept="image/*") only filters the browser’s file picker. Anyone can bypass it, so the server must still validate every file.
Handling Uploads in Slim
Section titled “Handling Uploads in Slim”Accessing Uploaded Files
Section titled “Accessing Uploaded Files”$uploadedFiles = $request->getUploadedFiles();$uploadedFile = $uploadedFiles['userfile'] ?? null;$uploadedFile is null when no file was sent. This also happens when the request is larger than PHP’s post_max_size setting: PHP then discards the whole request body. Always check for null before using the file.
UploadedFile Methods
Section titled “UploadedFile Methods”| Method | Description |
|---|---|
getError() | Upload error code. UPLOAD_ERR_OK (0) means success |
getSize() | File size in bytes |
getClientFilename() | Original filename, chosen by the user. Never trust it |
getClientMediaType() | Media type reported by the browser. Never trust it |
getStream() | The file’s content; getStream()->getMetadata('uri') is its temporary path |
moveTo($path) | Move the file from the temporary folder to a permanent location |
PHP Upload Limits
Section titled “PHP Upload Limits”PHP checks two php.ini settings before your code runs. When a file breaks one of them, your code receives a different result for each:
| Setting | Default | When exceeded |
|---|---|---|
upload_max_filesize | 2M | The file arrives, but getError() returns UPLOAD_ERR_INI_SIZE and the file’s content is missing |
post_max_size | 8M | PHP discards the whole request body: getUploadedFiles() returns an empty array, and getParsedBody() is empty too |
post_max_size limits the entire request, including the other form fields, so it must be larger than upload_max_filesize. Otherwise a file that is small enough for upload_max_filesize can still empty the whole request.
To change these values, edit the php.ini file that Apache uses (phpinfo() shows its path under “Loaded Configuration File”), then restart Apache.
Your own size check (for example, 2 MB for product images) only runs for files that pass both limits. Set the PHP limits higher than your own limit so that users see your error message instead of a generic one.
Validation (Required!)
Section titled “Validation (Required!)”Never trust user input. Always validate:
- Upload errors:
getError()must returnUPLOAD_ERR_OK.UPLOAD_ERR_INI_SIZEmeans the file exceeded PHP’supload_max_filesizesetting. - File size: compare
getSize()against your maximum allowed size. - File type: detect the type from the file’s content and compare it against a whitelist.
Upload Error Codes
Section titled “Upload Error Codes”getError() returns one of PHP’s UPLOAD_ERR_* constants. Only UPLOAD_ERR_OK means the file can be used.
| Constant | Value | Meaning |
|---|---|---|
UPLOAD_ERR_OK | 0 | The upload succeeded |
UPLOAD_ERR_INI_SIZE | 1 | The file is larger than upload_max_filesize |
UPLOAD_ERR_FORM_SIZE | 2 | The file is larger than the form’s hidden MAX_FILE_SIZE field |
UPLOAD_ERR_PARTIAL | 3 | Only part of the file arrived, for example because the connection dropped |
UPLOAD_ERR_NO_FILE | 4 | The form was submitted without choosing a file |
UPLOAD_ERR_NO_TMP_DIR | 6 | The server has no temporary folder configured |
UPLOAD_ERR_CANT_WRITE | 7 | The server could not write the file to disk |
UPLOAD_ERR_EXTENSION | 8 | A PHP extension stopped the upload |
Codes 1, 2, and 4 are caused by the user, so give them a specific message (“The file is too large”, “No file was selected”). Codes 3, 6, 7, and 8 point to a network or server problem, and a general “Error uploading file” message is enough.
Detecting the Real File Type
Section titled “Detecting the Real File Type”The browser sends the media type returned by getClientMediaType(), and an attacker can set it to any value. PHP’s Fileinfo extension detects the type by reading the file’s content instead:
$finfo = new finfo(FILEINFO_MIME_TYPE);$detectedType = $finfo->file($uploadedFile->getStream()->getMetadata('uri'));Run this check before calling moveTo(), while the file is still in PHP’s temporary folder.
The content check is not enough on its own. finfo only reads the first bytes of the file, so an attacker can build a file that starts like a real JPEG and contains PHP code further down. Such a file is harmless as long as it is saved with a .jpg extension, because the web server serves .jpg files as images and never runs them as PHP. What keeps it harmless is that your code, not the client, chooses the extension (see Moving Files).
Moving Files
Section titled “Moving Files”Uploaded files are stored temporarily and deleted after the request ends. You must move them to permanent storage with moveTo():
$uploadedFile->moveTo($targetPath);When choosing the target path:
- Create the upload directory with write permissions.
- Never use the client’s filename: it could contain a path such as
../../config/settings.php, or collide with an existing file. - Generate a random name, for example with
bin2hex(random_bytes(16)). - Choose the extension from the detected file type (for example,
image/jpegbecomes.jpg), never from the client’s filename.
Saving and Displaying Uploaded Files
Section titled “Saving and Displaying Uploaded Files”Store the Path, Not the File
Section titled “Store the Path, Not the File”The file itself stays on disk. The database stores only where to find it, in a VARCHAR column, for example uploads/products/product_9f3c1a.jpg. Keeping files out of the database keeps the tables small and lets the web server send images directly, without a PHP script reading them from the database.
Store the path relative to the public/ folder rather than as a full URL or an absolute disk path. The same row then still works if the application moves to another folder or server.
Build the URL in the View
Section titled “Build the URL in the View”The browser needs a URL, not a disk path. Add the application’s base URL and the public/ folder in front of the stored path, and escape the result like any other value:
<img src="<?= APP_BASE_URL ?>/public/<?= hs($imagePath) ?>" alt="Product image">On disk, the same file is at APP_BASE_DIR_PATH . '/public/' . $imagePath. Use the disk path when PHP works with the file (moving or deleting it) and the URL when the browser displays it.
Deleting a Record Does Not Delete Its File
Section titled “Deleting a Record Does Not Delete Its File”When a database row is deleted, either directly or through a foreign key with ON DELETE CASCADE, the file it pointed to stays on disk. Over time, these orphaned files take up space. To remove a file together with its row, read the path before deleting the row, then delete the file with unlink():
$path = APP_BASE_DIR_PATH . '/public/' . $imagePath;if (is_file($path)) { unlink($path);}Security Best Practices
Section titled “Security Best Practices”Accepting files without validation is a security hole. If an attacker can save a file named shell.php in a folder the web server serves, visiting its URL runs the attacker’s code on your server.
Secure Process
Section titled “Secure Process”- Check
getError()before processing the uploaded file. - Only allow specific file types using a whitelist, checked against the file’s content.
- Set reasonable file size limits (e.g., 2 MB).
- Generate a random filename, with an extension chosen by your code.
- Store files that the browser must display (such as product images) in the
public/folder, for examplepublic/uploads/. Because these files are served directly, steps 2 and 4 are what keep a.phpfile out of that folder.
Upload Process Flow
Section titled “Upload Process Flow”User selects file → Browser POST request → Slim route→ Get uploaded file object (null check) → Check upload error→ Validate size → Detect type from content → Generate safe filename→ Move to permanent location → Redirect with a flash message