Skip to content

File Uploads with Slim Framework and PHP

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.


  1. method="POST": file uploads must use POST.
  2. enctype="multipart/form-data": without it, the browser sends only the filename, not the file’s content.
  3. <input type="file">: creates the file selection control.
  4. The input’s name attribute: the key used to read the file on the server.
<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.


$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.

MethodDescription
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 checks two php.ini settings before your code runs. When a file breaks one of them, your code receives a different result for each:

SettingDefaultWhen exceeded
upload_max_filesize2MThe file arrives, but getError() returns UPLOAD_ERR_INI_SIZE and the file’s content is missing
post_max_size8MPHP 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.


Never trust user input. Always validate:

  1. Upload errors: getError() must return UPLOAD_ERR_OK. UPLOAD_ERR_INI_SIZE means the file exceeded PHP’s upload_max_filesize setting.
  2. File size: compare getSize() against your maximum allowed size.
  3. File type: detect the type from the file’s content and compare it against a whitelist.

getError() returns one of PHP’s UPLOAD_ERR_* constants. Only UPLOAD_ERR_OK means the file can be used.

ConstantValueMeaning
UPLOAD_ERR_OK0The upload succeeded
UPLOAD_ERR_INI_SIZE1The file is larger than upload_max_filesize
UPLOAD_ERR_FORM_SIZE2The file is larger than the form’s hidden MAX_FILE_SIZE field
UPLOAD_ERR_PARTIAL3Only part of the file arrived, for example because the connection dropped
UPLOAD_ERR_NO_FILE4The form was submitted without choosing a file
UPLOAD_ERR_NO_TMP_DIR6The server has no temporary folder configured
UPLOAD_ERR_CANT_WRITE7The server could not write the file to disk
UPLOAD_ERR_EXTENSION8A 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.

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).


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/jpeg becomes .jpg), never from the client’s filename.

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.

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);
}

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.

  1. Check getError() before processing the uploaded file.
  2. Only allow specific file types using a whitelist, checked against the file’s content.
  3. Set reasonable file size limits (e.g., 2 MB).
  4. Generate a random filename, with an extension chosen by your code.
  5. Store files that the browser must display (such as product images) in the public/ folder, for example public/uploads/. Because these files are served directly, steps 2 and 4 are what keep a .php file out of that folder.

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