Langkah 7 dari 9
Menampilkan Gambar dari Folder Writable
Karena gambar disimpan di luar public, buat method show() yang hanya menerima pola nama tertentu:
if (! preg_match('/^[a-zA-Z0-9_-]+\.(?:jpg|jpeg|png|webp)$/i', $fileName)) {
throw PageNotFoundException::forPageNotFound();
}
$uploadDirectory = realpath(WRITEPATH . 'uploads/images');
$imagePath = realpath(WRITEPATH . 'uploads/images/' . $fileName);
if ($uploadDirectory === false || $imagePath === false
|| ! str_starts_with($imagePath, $uploadDirectory . DIRECTORY_SEPARATOR)) {
throw PageNotFoundException::forPageNotFound();
}
Perbandingan hasil realpath() membantu memastikan file masih berada di dalam direktori upload. Setelah itu, periksa MIME type lagi dan kirim header X-Content-Type-Options: nosniff sebelum membaca file.
Pada View, tampilkan hasil dengan URL controller:
<img src="<?= site_url('gambar/' . session('uploadedImage')) ?>"
alt="Gambar yang berhasil diunggah">
