After this lesson you can validate an uploaded image, generate a storage name and keep the file outside the public directory. An upload is more than another text field. It introduces filesystem state, content inspection, resource limits and a later decision about whether a visitor may retrieve the stored file.
Define a narrow local upload task
Our fictional bookshop accepts a PNG or JPEG cover into private learning storage. The example does not yet associate the stored file with a book record or provide a download endpoint. Keeping those unfinished pieces explicit prevents a successful upload from being mistaken for a complete cover-management feature.
Create app/Controllers/Covers.php with this class. It uses CodeIgniter's file-specific validation rules before moving the uploaded temporary file.
<?php
namespace App\Controllers;
class Covers extends BaseController
{
public function create()
{
$rules = ['cover' => [
'uploaded[cover]', 'is_image[cover]',
'mime_in[cover,image/png,image/jpeg]', 'max_size[cover,512]',
]];
if (! $this->validateData([], $rules)) {
return $this->response->setStatusCode(422)->setJSON(['error' => 'Invalid cover.']);
}
$file = $this->request->getFile('cover');
if (! $file->isValid() || $file->hasMoved()) {
return $this->response->setStatusCode(422)->setJSON(['error' => 'Upload unavailable.']);
}
$file->move(WRITEPATH . 'uploads', $file->getRandomName());
return $this->response->setStatusCode(201)->setJSON(['stored' => true]);
}
}This class passed PHP lint and was exercised with real multipart HTTP requests. A small PNG fixture returned 201 with stored true. A text file returned 422 with Invalid cover. The file size policy is a course choice, expressed in the file-validation rule's documented units, rather than a platform benchmark.
Connect the POST boundary
For the isolated local exercise, add this route:
$routes->post('covers', 'Covers::create', ['filter' => 'csrf']);It uses the same browser CSRF boundary as the title form. It is still not an authorized public upload service. The final project applies deny-all protection before any external sharing. Do not open uploads while assuming a token proves that the sender is an editor.
A browser form needs method post, an action targeting covers and enctype multipart/form-data. Its file input must use the name cover to match the rules and getFile call. Include a current generated CSRF token, as in the book form. A plain text form encoding does not send the file content in the expected upload structure.
Inspect content rather than trusting names
A filename ending in png is not proof of image content. The example combines uploaded, is_image, mime_in and max_size. Each rule addresses a different property. Use uploaded rather than a generic required rule for the file field, because uploaded-file validation reads the request's file information.
The example checks isValid and hasMoved before moving. It generates a new name rather than using the client-supplied filename as a storage path. Original names may contain misleading extensions or troublesome path characters. Even a cleaned name is not an authorization decision about where a file should be stored or who may download it.
Keep storage and publication separate
WRITEPATH places the destination outside public. That prevents direct ordinary web-server delivery from being the accidental publication policy. A later download action would need to choose the file by an application-owned identifier, check access, select an appropriate content type and avoid accepting arbitrary filesystem paths from callers.
A valid image can still contain unwanted content or sensitive metadata. The current rules do not establish moderation, malware scanning or privacy review. Larger applications may need additional processing and quotas. Describe those needs as unfinished responsibilities rather than claiming image validation guarantees every kind of safety.
Filesystem writes and database writes are also different operations. If you later save a cover filename in books, define what happens when the move succeeds but the database update fails, or when a book is deleted. Without a cleanup policy, unused uploads can accumulate even though each individual request looked successful.
Verify rejected requests leave no new file
A good upload check records the private upload directory state, submits an invalid file and confirms that no new stored file appears. A response-only check can miss a move performed before validation. In this implementation, the invalid branch returns before getFile and move.
The fetched official Working with Uploaded Files guide and Validation guide support the APIs used here. The private-cover task is deliberately narrower than a public media library. Its real HTTP checks prove the two tested cases, not every possible file format or hostile payload.
Common mistakes
Trusting the extension alone ignores content. Using the original filename as a path lets client-controlled naming influence storage. Omitting multipart encoding means the request does not contain the expected upload. Storing files under public publishes them before an access decision. Finally, forgetting cleanup when a database operation fails creates orphaned files.
Exercise
Explain why a renamed text file should not be accepted as a PNG. Identify where validation stops the request and where the generated name is chosen. Then list the missing responsibility before a stored cover can appear on a book detail page.
Show an answer
The rules inspect uploaded content rather than trusting the extension. A failed rule returns 422 before moving. getRandomName provides the storage name. The application still needs a reviewed association between the private file and a book, plus a safe serving and access policy. Upload success alone does not publish or attach a cover.
Previous lesson · Next lesson · Related: explicit routes · Related: security boundaries
Key points
- Use file-specific rules rather than trusting names.
- Generate storage names and keep uploads outside public.
- Cover association, download policy and cleanup remain separate responsibilities.