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 clean access to uploaded files through PSR-7 Request objects.
HTML Upload Form
Section titled “HTML Upload Form”Required Form Attributes
Section titled “Required Form Attributes”method="POST"- File uploads must use POSTenctype="multipart/form-data"- Required for file transmission<input type="file">- Creates file selection interfacenameattribute - Key to access file on 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>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 Methods
Section titled “UploadedFile Methods”| Method | Description |
|---|---|
getError() | Upload error code. UPLOAD_ERR_OK (0) = success |
getSize() | File size in bytes |
getClientFilename() | Original filename. Never trust! |
getClientMediaType() | Media type from browser. Don’t fully trust! |
moveTo($path) | Move file from temp to permanent location |
Validation (Required!)
Section titled “Validation (Required!)”Never trust user input. Always validate:
- Upload Errors:
$uploadedFile->getError() === UPLOAD_ERR_OK - File Size: Compare against maximum allowed size
- File Type: Check media type against whitelist
Moving Files
Section titled “Moving Files”Uploaded files are stored temporarily and deleted after script execution. You must move them to permanent storage.
Key Points:
- Create uploads directory with write permissions
- Sanitize filenames (user’s filename could be malicious:
../../etc/passwd) - Generate unique filenames to prevent collisions
- Use
moveTo()method
$uploadedFile->moveTo($targetPath);Security Best Practices
Section titled “Security Best Practices”Critical: Accepting files without validation is a security hole. Malicious users can upload PHP shells.
Secure Process
Section titled “Secure Process”- Check Upload Errors - Verify
getError()first - Safe Directory - Store outside web root (public folder)
- ✅ Good:
my-project/uploads/ - ❌ Bad:
my-project/public/uploads/
- ✅ Good:
- Validate File Type - Use whitelist of allowed types
- Validate File Size - Set reasonable limits (e.g., 5MB)
- Generate Secure Filenames - Never use client filenames
Upload Process Flow
Section titled “Upload Process Flow”User selects file → Browser POST request → Slim route→ Get uploaded file object → Check errors→ Validate size & type → Generate safe filename→ Move to permanent location → Success response