Lab 7: Implementing File Uploads
Additional Resources
Section titled “Additional Resources”- File Uploads with Slim Framework and PHP
- The Result Pattern
- Working with the BaseController class
- Working with the BaseModel class
- Database Tables
- PHP File Upload ↗
- PHP Fileinfo (finfo) ↗
- Slim 4 Uploaded Files ↗
- OWASP File Upload Cheat Sheet ↗
Overview
Section titled “Overview”In this lab, you will add secure image uploads to your admin panel.
- In Part I, you will build a reusable
FileUploadHelperclass that validates an uploaded file and saves it under a safe name, then use it on an upload page that displays a gallery of the uploaded images. - In Part II, you will reuse the same helper to give each product an image. The image is uploaded from the product edit page you built in Lab 6 and recorded in the
product_imagestable, where later labs (Live Search, Shopping Cart) read it.
Learning Objectives
Section titled “Learning Objectives”By completing this lab, you will:
- Build an upload form with
enctype="multipart/form-data"and read the file with Slim’sgetUploadedFiles(). - Validate an upload: PHP upload errors, file size, and the file’s real content type.
- Explain why the browser-reported media type and the client’s filename must never be trusted.
- Save files under random names with an extension chosen by the server.
- Return success or failure from a helper class with the Result pattern.
- Link an uploaded image to a product in the database.
Prerequisites
Section titled “Prerequisites”Before starting this lab, ensure you have:
- Completed Lab 6: Implementing UPDATE and DELETE Operations, including the product edit page.
- Completed Lab 4: Session Middleware and Flash Messages.
- The
Resultclass from the starter template (app/Helpers/Core/Result.php). TheFileUploadHelperreturns aResultso the controller can tell a successful upload from a failed one. - Read The Result Pattern and File Uploads with Slim Framework and PHP.
Part I: The FileUploadHelper and an Upload Page
Section titled “Part I: The FileUploadHelper and an Upload Page”Step 1: Create the Uploads Directories
Section titled “Step 1: Create the Uploads Directories”Objective: Create the folders where uploaded files are stored.
Instructions:
- Navigate to your
public/directory - Create the following folders:
public/└── uploads/ ├── images/ (Part I: upload page gallery) └── products/ (Part II: product images)Files in public/ can be served by the web server, which is how the browser displays the uploaded images. This is also why the helper must never save a file with an extension such as .php: the server would run it as code.
Step 2: Check PHP’s Upload Limits
Section titled “Step 2: Check PHP’s Upload Limits”Objective: Make sure PHP accepts the file sizes used in this lab’s tests.
PHP rejects an upload before your code runs if it exceeds one of two php.ini settings:
| Setting | Effect when exceeded |
|---|---|
upload_max_filesize | The file arrives with the error code UPLOAD_ERR_INI_SIZE |
post_max_size | PHP discards the whole request body, so getUploadedFiles() returns an empty array |
Instructions:
- Open the
php.inifile that Apache uses. If you are not sure which one it is,phpinfo()shows its path under “Loaded Configuration File”. - Check that
upload_max_filesizeis at least8Mandpost_max_sizeis larger thanupload_max_filesize(for example,10M) - If you changed a value, save the file and restart Apache
The helper you write allows at most 2 MB. With these settings, a 3 MB file reaches your code, so you can test your own size check.
Step 3: Create the FileUploadHelper Class
Section titled “Step 3: Create the FileUploadHelper Class”Objective: Create a reusable class that validates an uploaded file and saves it under a safe name.
Instructions:
- Navigate to your
app/Helpers/directory - Create a new file named
FileUploadHelper.php - Start from the following class structure:
<?php
namespace App\Helpers;
use App\Helpers\Core\Result;use finfo;use Psr\Http\Message\UploadedFileInterface;use RuntimeException;
class FileUploadHelper{ /** * Validate an uploaded file, save it under a random name, and return a Result. * * @param UploadedFileInterface $uploadedFile The uploaded file from the request * @param array $config Configuration options: * - 'directory' (string): Absolute path of the upload directory (required) * - 'allowedTypes' (array): Allowed media types mapped to the extension * to save them with, e.g. ['image/jpeg' => 'jpg'] (required) * - 'maxSize' (int): Maximum file size in bytes (required) * - 'filenamePrefix' (string): Prefix for generated filenames (default: 'upload_') * @return Result Success with ['filename' => ...], or failure with an error message */ public static function upload(UploadedFileInterface $uploadedFile, array $config): Result { // TODO: 1. Read the four configuration values from $config, using the defaults above. // If 'directory' or 'allowedTypes' is empty, or 'maxSize' is 0 or less, // return a failure.
// TODO: 2. Check the file's upload error code (see the table below).
// TODO: 3. Check that the file is not larger than the maximum size.
// TODO: 4. Detect the file's real media type from its content, and check // that it is one of the allowed types.
// TODO: 5. Generate a random filename: the prefix, 32 random hexadecimal // characters, a dot, and the extension mapped to the detected type.
// TODO: 6. Create the upload directory if it does not exist.
// TODO: 7. Move the file into the upload directory under the new name. // If moving fails, return a failure.
// TODO: 8. Return a success with the new filename in the data. }}- Implement the TODOs
- Save the file
Error Messages:
| Situation | Failure Message |
|---|---|
| A required configuration value is missing | Upload configuration is incomplete. |
Error code UPLOAD_ERR_INI_SIZE or UPLOAD_ERR_FORM_SIZE | The file is larger than the server allows. |
Error code UPLOAD_ERR_NO_FILE | No file was selected. |
Any other error code except UPLOAD_ERR_OK | Error uploading file. |
The file is larger than maxSize | The file must not be larger than 2 MB. (use the configured size in MB) |
The detected type is not in allowedTypes | Only JPEG, PNG, and GIF images are allowed. |
| The upload directory cannot be created | Upload directory could not be created. |
| Moving the file fails | Failed to save the uploaded file. |
Use “File uploaded successfully.” as the success message.
Functions You Will Need:
| TODO | Function or Expression | Purpose |
|---|---|---|
| 1 | $config['key'] ?? $default | Read a configuration value, or use a default when the key is missing |
| 2 | $uploadedFile->getError() | Return the upload’s UPLOAD_ERR_* code |
| 3 | $uploadedFile->getSize() | Return the file size in bytes |
| 3 | round($bytes / (1024 * 1024), 1) | Convert a size in bytes to MB, rounded to one decimal |
| 4 | finfo (see below) | Detect the media type from the file’s content |
| 4 | array_key_exists($key, $array) | Check whether an array has the given key |
| 5 | bin2hex(random_bytes(16)) | Generate 32 random hexadecimal characters |
| 6 | is_dir($path) | Check whether a folder exists |
| 6 | mkdir($path, 0755, true) | Create a folder; true also creates missing parent folders. Returns false on failure |
| 7 | $uploadedFile->moveTo($path) | Move the file to its final location. Throws a RuntimeException on failure |
Detect the type while the file is still in PHP’s temporary folder, before you move it. finfo needs the file’s temporary path, which the file’s stream provides:
$finfo = new finfo(FILEINFO_MIME_TYPE);$detectedType = $finfo->file($uploadedFile->getStream()->getMetadata('uri'));Hints:
- The browser chooses the value returned by
getClientMediaType(), and an attacker can send any value. That is why TODO 4 usesfinfoinstead. - In
allowedTypes, the media types are the keys and the extensions are the values:['image/jpeg' => 'jpg', ...].in_array()searches the values, soin_array($detectedType, $allowedTypes)compares'image/jpeg'with'jpg'and rejects every file. Check the key instead, then use$allowedTypes[$detectedType]as the extension in TODO 5. - Never take the extension from
getClientFilename(). A file namedshell.phpwith a JPEG media type would otherwise be saved as.phpinpublic/. - Unlike
uniqid(), which is based on the current time,random_bytes()cannot be guessed.
Step 4: Create the Upload Form View
Section titled “Step 4: Create the Upload Form View”Objective: Create an admin page with an upload form and a gallery of uploaded images.
Instructions:
- Navigate to
app/Views/admin/and create anupload/folder - Inside
app/Views/admin/upload/, create a file nameduploadView.php - Copy and paste the following code:
<?php
use App\Helpers\SessionManager;use App\Helpers\ViewHelper;
ViewHelper::loadAdminHeader($title);
$uploadedFiles = SessionManager::get('uploaded_files', []);?>
<div class="card mb-4"> <div class="card-header"> <h5>Upload an Image</h5> </div> <div class="card-body"> <form method="POST" action="<?= APP_BASE_URL ?>/admin/upload" enctype="multipart/form-data"> <div class="mb-3"> <label for="myfile" class="form-label">Choose a file:</label> <input type="file" class="form-control" id="myfile" name="myfile" accept="image/jpeg,image/png,image/gif" required> <div class="form-text"> JPEG, PNG, or GIF, up to 2 MB. </div> </div> <button type="submit" class="btn btn-primary">Upload File</button> </form> </div></div>
<?php if (!empty($uploadedFiles)): ?><div class="card"> <div class="card-header"> <h5>Uploaded Files</h5> </div> <div class="card-body"> <div class="row"> <?php foreach (array_reverse($uploadedFiles) as $filename): ?> <div class="col-md-4 mb-3"> <div class="card"> <img src="<?= APP_BASE_URL ?>/public/uploads/images/<?= hs($filename) ?>" class="card-img-top" alt="Uploaded image" style="height: 200px; object-fit: cover;"> <div class="card-body"> <p class="card-text small text-muted"><?= hs($filename) ?></p> </div> </div> </div> <?php endforeach; ?> </div> </div></div><?php endif; ?>
<?php ViewHelper::loadAdminFooter(); ?>- Save the file
The accept attribute only filters the browser’s file picker. Anyone can bypass it, so it does not replace the checks in FileUploadHelper.
Step 5: Create the UploadController
Section titled “Step 5: Create the UploadController”Objective: Create a controller that displays the upload page and processes uploads with FileUploadHelper.
Instructions:
- Navigate to your
app/Controllers/directory - Create a new file named
UploadController.php - Start from the following class structure:
<?php
namespace App\Controllers;
use App\Helpers\FileUploadHelper;use App\Helpers\FlashMessage;use App\Helpers\SessionManager;use DI\Container;use Psr\Http\Message\ResponseInterface as Response;use Psr\Http\Message\ServerRequestInterface as Request;use Psr\Http\Message\UploadedFileInterface;
class UploadController extends BaseController{ // TODO: Add a constructor that calls the parent constructor.
/** * Display the upload form (GET /admin/upload). */ public function index(Request $request, Response $response, array $args): Response { // TODO: Render 'admin/upload/uploadView.php' with the title 'File Upload' }
/** * Process the upload form (POST /admin/upload). */ public function upload(Request $request, Response $response, array $args): Response { // TODO: 1. Get the uploaded file named 'myfile' from the request. // If there is none, set an error flash message using the FlashMessage // helper class ("No file was received. It may be larger than the // server allows.") and redirect to 'upload.index'.
// TODO: 2. Create the $config array (see the table below).
// TODO: 3. Upload the file using the FileUploadHelper class.
// TODO: 4. If the upload succeeded: // - add the new filename to the 'uploaded_files' array in the session // - set a success flash message using the FlashMessage helper class // Otherwise, set an error flash message with the result's message.
// TODO: 5. Redirect to 'upload.index' }}- Implement the TODOs
- Save the file
Configuration:
| Key | Value |
|---|---|
directory | APP_BASE_DIR_PATH . '/public/uploads/images' |
allowedTypes | ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif'] |
maxSize | 2 * 1024 * 1024 (2 MB in bytes) |
filenamePrefix | 'upload_' |
Hints:
- When the request is larger than
post_max_size,getUploadedFiles()returns an empty array. Check that the value you read is anUploadedFileInterfacebefore passing it to the helper; passingnullthrows aTypeError. - The gallery stores filenames in the session, so it is emptied when the session ends. Part II stores product images in the database instead.
Step 6: Register the Upload Routes and Sidebar Link
Section titled “Step 6: Register the Upload Routes and Sidebar Link”Objective: Make the upload page reachable from the admin panel.
Instructions:
- Open
app/Routes/web-routes.phpand add the following import at the top:
use App\Controllers\UploadController;- Inside the existing
/admingroup, add two routes:
$app->group('/admin', function ($group) { // ... existing routes ...
// TODO: Add GET route for /upload // - Controller: UploadController::class, 'index' // - Named route: 'upload.index'
// TODO: Add POST route for /upload // - Controller: UploadController::class, 'upload' // - Named route: 'upload.process'});- Save the file
- Open
app/Views/admin/adminHeader.php, find the navigation list (<ul class="nav flex-column ...">) in the sidebar, and add a new item after the existing links:
<li class="nav-item"> <a class="nav-link" href="<?= APP_BASE_URL ?>/admin/upload"> File Upload </a></li>- Save the file
Step 7: Test the Upload Page
Section titled “Step 7: Test the Upload Page”- Visit
http://localhost/your-app-name/admin/uploadand check that the “File Upload” link appears in the sidebar - Upload a JPEG, PNG, or GIF image smaller than 2 MB. You should see a success message, and the image should appear in the gallery.
- Open
public/uploads/images/. The file should have a name likeupload_9f3c...e1.jpg, not its original name. - Upload a
.txtor.pdffile. You should see “Only JPEG, PNG, and GIF images are allowed.” - Rename a text file from
notes.txttophoto.jpgand upload it. The browser reports it asimage/jpeg, but your content check should still reject it. - Upload an image between 2 MB and 8 MB. You should see “The file must not be larger than 2 MB.”
- Refresh the page after an upload. The message should not appear again, and no file should be uploaded twice.
Part II: Product Images
Section titled “Part II: Product Images”In this part, you will let administrators upload an image for each product from the product edit page. The image’s path is saved in the product_images table.
Step 8: Prepare the product_images Table
Section titled “Step 8: Prepare the product_images Table”Objective: Make sure the product_images table exists and deletes its rows when their product is deleted.
Instructions:
- Open phpMyAdmin, select your project database, and click on the “SQL” tab
- Execute the following statements:
DROP TABLE IF EXISTS product_images;
CREATE TABLE product_images ( id INT AUTO_INCREMENT PRIMARY KEY, product_id INT NOT NULL, file_path VARCHAR(255) NOT NULL, is_primary BOOLEAN NOT NULL DEFAULT FALSE, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE);ON DELETE CASCADE deletes a product’s image rows when the Delete button from Lab 6 deletes the product. Without it, MySQL refuses to delete any product that has an image.
file_path stores the path relative to the public/ folder, for example uploads/products/product_9f3c...e1.jpg. A view builds the image URL by adding APP_BASE_URL . '/public/' in front of it.
Step 9: Add Image Methods to the ProductsModel
Section titled “Step 9: Add Image Methods to the ProductsModel”Objective: Add methods that read and save a product’s main image.
Instructions:
- Open
app/Domain/Models/ProductsModel.php - Add the following methods:
/** * Return the file path of the product's primary image, or null if it has none. */public function getPrimaryImage(int $productId): ?string{ // TODO: Select the file_path of the product's image where is_primary is 1. // Return the path, or null if there is no row.}
/** * Save a new image for the product and make it the primary image. */public function setPrimaryImage(int $productId, string $filePath): void{ // TODO: 1. Mark all existing images of this product as not primary.
// TODO: 2. Insert the new image with is_primary set to 1.}- Implement the TODOs
- Save the file
Older images stay in the table as non-primary images. Only one image per product has is_primary = 1, and that is the one the store displays.
Step 10: Add the uploadImage() Method to the ProductsController
Section titled “Step 10: Add the uploadImage() Method to the ProductsController”Objective: Process image uploads from the product edit page, and show the current image on that page.
Instructions:
- Open
app/Controllers/ProductsController.php - Add the following imports at the top:
use App\Helpers\FileUploadHelper;use Psr\Http\Message\UploadedFileInterface;- In the
edit()method from Lab 6, add an'image'key to the$dataarray. Its value is the product’s primary image path fromgetPrimaryImage(). - Add the following method:
/** * Upload a new image for a product (POST /admin/products/{id}/image). */public function uploadImage(Request $request, Response $response, array $args): Response{ // TODO: 1. Get the product ID from the route arguments. // If the product does not exist, set an error flash message using the // FlashMessage helper class and redirect to 'products.index'.
// TODO: 2. Get the uploaded file named 'image' from the request. // If there is none, set an error flash message using the FlashMessage // helper class and redirect back to 'products.edit'.
// TODO: 3. Upload the file using the FileUploadHelper class, with the same // configuration as in Step 5 except: // - 'directory' => APP_BASE_DIR_PATH . '/public/uploads/products' // - 'filenamePrefix' => 'product_'
// TODO: 4. If the upload succeeded: // - save 'uploads/products/' followed by the new filename as the // product's primary image // - set a success flash message using the FlashMessage helper class // Otherwise, set an error flash message with the result's message.
// TODO: 5. Redirect back to 'products.edit' for this product.}- Implement the TODOs
- Save the file
Step 11: Register the Product Image Route
Section titled “Step 11: Register the Product Image Route”Objective: Add the route that the image form submits to.
Instructions:
- Open
app/Routes/web-routes.php - Inside the
/admingroup, next to the other product routes, add:
// TODO: Add POST route for /products/{id}/image// - Controller: ProductsController::class, 'uploadImage'// - Named route: 'products.image'- Save the file
Step 12: Add the Image Form to the Edit Page
Section titled “Step 12: Add the Image Form to the Edit Page”Objective: Display the product’s current image and a form to replace it.
Instructions:
- Open
app/Views/admin/products/products.EditView.php - After the closing
</form>tag of the edit form, add the following code:
<div class="card mt-4"> <div class="card-header"> <h5 class="mb-0">Product Image</h5> </div> <div class="card-body"> <?php if ($image): ?> <img src="<?= APP_BASE_URL ?>/public/<?= hs($image) ?>" alt="<?= hs($product['name']) ?>" class="img-thumbnail mb-3" style="max-height: 200px;"> <?php else: ?> <p class="text-muted">This product has no image yet.</p> <?php endif; ?>
<form method="POST" action="<?= APP_BASE_URL ?>/admin/products/<?= $product['id'] ?>/image" enctype="multipart/form-data"> <div class="mb-3"> <label for="image" class="form-label">Upload a new image</label> <input type="file" class="form-control" id="image" name="image" accept="image/jpeg,image/png,image/gif" required> </div> <button type="submit" class="btn btn-secondary">Upload Image</button> </form> </div></div>- Save the file
The image form must be outside the edit form: HTML does not allow a form inside another form. Each form submits to its own route.
Step 13: Test the Product Images
Section titled “Step 13: Test the Product Images”- Visit
/admin/products, click Edit on a product, and check that the page shows “This product has no image yet.” - Upload an image. You should be redirected back to the same edit page with a success message, and the image should be displayed.
- Upload a second image. It should replace the first one on the page.
- In phpMyAdmin, browse
product_images. The product should have two rows, and only the newest hasis_primary = 1. - Try uploading a text file renamed to
.jpg. You should see the error message, and the current image should not change. - Delete the product from the product list. Its rows in
product_imagesshould be deleted too.
Verification Checklist
Section titled “Verification Checklist”Before submitting your lab, verify the following:
-
FileUploadHelper.phpexists inapp/Helpers/and returns aResult - The helper detects the type from the file’s content and never uses the client’s filename or extension
- Saved files have random names with an extension chosen by the server
- Every rejected upload shows the matching error message as a flash message
- A request with no file shows an error instead of crashing
- The upload page gallery displays uploaded images
- The product edit page uploads an image, saves it in
product_images, and displays it - Deleting a product also deletes its image rows