<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class Images extends Controller
{
/**
* index function
*
* Renders an image specified by parameters, while keeping the original path hidden.
* Images are usually uploaded to app/writable/uploads
* I created an 404 image and saved it to 'writable/uploads/' in case the called image is not available.
* The url to your fotos you would use in an img-tag would be eg 'https://yourdomain.com/images/subfolder/imagename.jpg'
* Add a Route to 'config/routes': $routes->get('images/(:alphanum)/(:segment)/(:segment)', 'Images::index/$1/$2/$3');
*
* @param string|false $folder1 - The first subfolder.
* @param string|false $folder2 - The second subfolder (optional).
* @param string|false $filename - The name of the image file.
*
* @return mixed - The image binary content and appropriate headers if successful; otherwise, a redirect or a 404 error message.
*/
public function index($folder1=false, $folder2=false, $filename=false)
{
// Ensure the user is logged in
if (auth()->loggedIn()) {
// Construct the full path to the image file
if ($filename == FALSE) {
$filename = $folder2;
$fullpath = WRITEPATH . 'uploads/' . $folder1 . '/' . $filename;
} else {
$fullpath = WRITEPATH . 'uploads/' . $folder1 . '/' . $folder2 . '/' . $filename;
}
// Check if the image file exists and show a 404 image if not.
if (! file_exists($fullpath)) { $fullpath = WRITEPATH . 'uploads/' . '404image.png';}
// Load the filesystem helper
helper("filesystem");
// Create a file object
$file = new \CodeIgniter\Files\File($fullpath, true);
// Read the file and stream its binary content to the response
$binary = readfile($fullpath);
// Set appropriate headers and return the response
return $this->response
->setHeader('Content-Type', $file->getMimeType())
->setHeader('Content-disposition', 'inline; filename="' . $file->getBasename() . '"')
->setStatusCode(200)
->setBody($binary);
} else {
// If the user is not logged in, redirect to the homepage
return redirect()->to('/');
}
}
}