Skip to content

Lab 7: Implementing File Uploads

In this lab, you will add secure image uploads to your admin panel.

  • In Part I, you will build a reusable FileUploadHelper class 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_images table, where later labs (Live Search, Shopping Cart) read it.

By completing this lab, you will:

  • Build an upload form with enctype="multipart/form-data" and read the file with Slim’s getUploadedFiles().
  • 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.

Before starting this lab, ensure you have:


Part I: The FileUploadHelper and an Upload Page

Section titled “Part I: The FileUploadHelper and an Upload Page”

Objective: Create the folders where uploaded files are stored.

Instructions:

  1. Navigate to your public/ directory
  2. 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.


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:

SettingEffect when exceeded
upload_max_filesizeThe file arrives with the error code UPLOAD_ERR_INI_SIZE
post_max_sizePHP discards the whole request body, so getUploadedFiles() returns an empty array

Instructions:

  1. Open the php.ini file that Apache uses. If you are not sure which one it is, phpinfo() shows its path under “Loaded Configuration File”.
  2. Check that upload_max_filesize is at least 8M and post_max_size is larger than upload_max_filesize (for example, 10M)
  3. 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.


Objective: Create a reusable class that validates an uploaded file and saves it under a safe name.

Instructions:

  1. Navigate to your app/Helpers/ directory
  2. Create a new file named FileUploadHelper.php
  3. Start from the following class structure:
app/Helpers/FileUploadHelper.php
<?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.
}
}
  1. Implement the TODOs
  2. Save the file

Error Messages:

SituationFailure Message
A required configuration value is missingUpload configuration is incomplete.
Error code UPLOAD_ERR_INI_SIZE or UPLOAD_ERR_FORM_SIZEThe file is larger than the server allows.
Error code UPLOAD_ERR_NO_FILENo file was selected.
Any other error code except UPLOAD_ERR_OKError uploading file.
The file is larger than maxSizeThe file must not be larger than 2 MB. (use the configured size in MB)
The detected type is not in allowedTypesOnly JPEG, PNG, and GIF images are allowed.
The upload directory cannot be createdUpload directory could not be created.
Moving the file failsFailed to save the uploaded file.

Use “File uploaded successfully.” as the success message.

Functions You Will Need:

TODOFunction or ExpressionPurpose
1$config['key'] ?? $defaultRead 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
3round($bytes / (1024 * 1024), 1)Convert a size in bytes to MB, rounded to one decimal
4finfo (see below)Detect the media type from the file’s content
4array_key_exists($key, $array)Check whether an array has the given key
5bin2hex(random_bytes(16))Generate 32 random hexadecimal characters
6is_dir($path)Check whether a folder exists
6mkdir($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 uses finfo instead.
  • In allowedTypes, the media types are the keys and the extensions are the values: ['image/jpeg' => 'jpg', ...]. in_array() searches the values, so in_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 named shell.php with a JPEG media type would otherwise be saved as .php in public/.
  • Unlike uniqid(), which is based on the current time, random_bytes() cannot be guessed.

Objective: Create an admin page with an upload form and a gallery of uploaded images.

Instructions:

  1. Navigate to app/Views/admin/ and create an upload/ folder
  2. Inside app/Views/admin/upload/, create a file named uploadView.php
  3. Copy and paste the following code:
app/Views/admin/upload/uploadView.php
<?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(); ?>
  1. 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.


Objective: Create a controller that displays the upload page and processes uploads with FileUploadHelper.

Instructions:

  1. Navigate to your app/Controllers/ directory
  2. Create a new file named UploadController.php
  3. Start from the following class structure:
app/Controllers/UploadController.php
<?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'
}
}
  1. Implement the TODOs
  2. Save the file

Configuration:

KeyValue
directoryAPP_BASE_DIR_PATH . '/public/uploads/images'
allowedTypes['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif']
maxSize2 * 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 an UploadedFileInterface before passing it to the helper; passing null throws a TypeError.
  • The gallery stores filenames in the session, so it is emptied when the session ends. Part II stores product images in the database instead.

Section titled “Step 6: Register the Upload Routes and Sidebar Link”

Objective: Make the upload page reachable from the admin panel.

Instructions:

  1. Open app/Routes/web-routes.php and add the following import at the top:
use App\Controllers\UploadController;
  1. Inside the existing /admin group, add two routes:
app/Routes/web-routes.php
$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'
});
  1. Save the file
  2. 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>
  1. Save the file

  1. Visit http://localhost/your-app-name/admin/upload and check that the “File Upload” link appears in the sidebar
  2. 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.
  3. Open public/uploads/images/. The file should have a name like upload_9f3c...e1.jpg, not its original name.
  4. Upload a .txt or .pdf file. You should see “Only JPEG, PNG, and GIF images are allowed.”
  5. Rename a text file from notes.txt to photo.jpg and upload it. The browser reports it as image/jpeg, but your content check should still reject it.
  6. Upload an image between 2 MB and 8 MB. You should see “The file must not be larger than 2 MB.”
  7. Refresh the page after an upload. The message should not appear again, and no file should be uploaded twice.

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.

Objective: Make sure the product_images table exists and deletes its rows when their product is deleted.

Instructions:

  1. Open phpMyAdmin, select your project database, and click on the “SQL” tab
  2. Execute the following statements:
SQL Statements to Create the product_images Table
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:

  1. Open app/Domain/Models/ProductsModel.php
  2. Add the following methods:
app/Domain/Models/ProductsModel.php
/**
* 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.
}
  1. Implement the TODOs
  2. 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:

  1. Open app/Controllers/ProductsController.php
  2. Add the following imports at the top:
use App\Helpers\FileUploadHelper;
use Psr\Http\Message\UploadedFileInterface;
  1. In the edit() method from Lab 6, add an 'image' key to the $data array. Its value is the product’s primary image path from getPrimaryImage().
  2. Add the following method:
app/Controllers/ProductsController.php
/**
* 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.
}
  1. Implement the TODOs
  2. Save the file

Objective: Add the route that the image form submits to.

Instructions:

  1. Open app/Routes/web-routes.php
  2. Inside the /admin group, next to the other product routes, add:
app/Routes/web-routes.php
// TODO: Add POST route for /products/{id}/image
// - Controller: ProductsController::class, 'uploadImage'
// - Named route: 'products.image'
  1. 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:

  1. Open app/Views/admin/products/products.EditView.php
  2. After the closing </form> tag of the edit form, add the following code:
app/Views/admin/products/products.EditView.php
<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>
  1. 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.


  1. Visit /admin/products, click Edit on a product, and check that the page shows “This product has no image yet.”
  2. Upload an image. You should be redirected back to the same edit page with a success message, and the image should be displayed.
  3. Upload a second image. It should replace the first one on the page.
  4. In phpMyAdmin, browse product_images. The product should have two rows, and only the newest has is_primary = 1.
  5. Try uploading a text file renamed to .jpg. You should see the error message, and the current image should not change.
  6. Delete the product from the product list. Its rows in product_images should be deleted too.

Before submitting your lab, verify the following:

  • FileUploadHelper.php exists in app/Helpers/ and returns a Result
  • 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