PHP Luminova: Private Storage File Renderer
Renders private storage files securely in the browser using the file Renderer class. Supports temporary signed URLs with expiration, browser caching, and optional image resizing.
The File Renderer class provides methods for serving files from private storage directories over HTTP.
It is designed to deliver files securely from non-public storage locations while managing HTTP headers, minimizing memory usage, and supporting browser caching. Files are served without exposing internal storage paths, helping protect private resources from unauthorized access.
Key capabilities include:
- Efficient streaming of large files in chunks to minimize memory usage.
- Signed tokens for temporary, time-limited access or non-expiring signed access.
- Automatic handling of cache-related headers, including
ETag,Last-Modified,Expires, andCache-Control, with support for304 Not Modifiedresponses. - Optional image resizing using the native PHP Imagick extension, the Peterujah\Media\NanoImage library, or a custom handler registered through Renderer::onResizeImage().
Luminova\Storage\Rendererprovides a CDN-style delivery layer for private storage files. It serves files from/writeable/storages/or a configured directory while supporting access control, making it suitable for secure media delivery and protected file distribution.
Examples
Serving Private Files
This example shows how to serve an image stored in a private directory so it can be viewed in a browser.
The image is not placed in a public folder. Instead, it is streamed securely through a controller route.
// /app/Controllers/Http/CdnController.php
namespace App\Controllers\Http;
use Luminova\Base\Controller;
use Luminova\Attributes\Prefix;
use Luminova\Attributes\Route;
use Luminova\Storage\Renderer;
use App\Errors\Controllers\AppError;
#[Prefix(pattern: '/cdn(:root)', onError: [AppError::class, 'onAssetsError'])]
class CDNController extends Controller
{
#[Route('/cdn/assets/images/([a-zA-Z0-9-]+\.(?:png|jpg|jpeg|gif|svg|webp))', methods: ['GET'])]
public function showImage(string $imageName): int
{
$sent = Renderer::storage('images') // Folder inside /writeable/storages/
->send($imageName); // e.g person.png
return $sent ? STATUS_SUCCESS : STATUS_ERROR;
}
}Access the image using:
https://example.com/cdn/assets/images/person.pngHow this works:
- Images are stored in
/writeable/storages/images/ - The route captures the image file name from the URI segment
Renderer::send()streams the file to the browser- If the file does not exist, a
404response is sent automatically andfalseis returned - The real file path is never exposed
Temporary Signed Files
You can generate a signed token for a private file.By default, the link automatically expires after a defined time.
Example:
Create a link that expires after 1 hour (3600 seconds).
use Luminova\Storage\Renderer;
$hash = Renderer::storage('images')
->sign('person.png', 3600);
if ($hash === false) {
// File does not exist, or the expiry is invalid
}
// Full URL used to access the image
$fullUrl = "https://example.com/cdn/private/image/{$hash}";Note:
- The
sign()method returns only a signed hash, orfalseif the file does not exist or$expiryis negative- Passing
nullor0as$expirycreates a hash that does not expire- The hash is an encrypted payload containing the file name, issue time, expiry duration, and timezone
- The hash uses URL-safe characters, so it can be placed directly in a URI segment
- You must append the hash to your route to form a full URL
- For long links, you may use a URL shortener if needed (e.g, https://tinyurl.com/)
Serving a Temporary Signed File
To serve a file using the signed hash, define a route that passes the hash to send(). The method detects that the value is a token, validates it, and outputs the file.
// /app/Controllers/Http/CdnController.php
namespace App\Controllers\Http;
use Luminova\Base\Controller;
use Luminova\Attributes\Prefix;
use Luminova\Attributes\Route;
use Luminova\Storage\Renderer;
use App\Errors\Controllers\AppError;
#[Prefix(pattern: '/cdn(:root)', onError: [AppError::class, 'onAssetsError'])]
class CDNController extends Controller
{
#[Route('/cdn/private/image/(:string)', methods: ['GET'])]
public function showSignedImages(string $imageHash): int
{
if (Renderer::storage('images')->send($imageHash)) {
return STATUS_SUCCESS;
}
return STATUS_ERROR;
}
}How this works:
- The route receives the signed hash from the URI segment
send()first checks whether the value is an existing file name; if not, it decodes it as a signed token- If the token is valid and not expired, the file is streamed to the client, and the cache lifetime is set to the remaining validity time of the hash (a hash without expiry is served with caching disabled)
- If invalid, malformed, expired, or the signed file no longer exists, a
404response is sent andfalseis returned
This approach allows you to share private files securely without making them public or permanent.
Inspecting a Signed Token
Use decode() to read a signed token without sending the file, for example to check validity or the remaining lifetime.
use Luminova\Storage\Renderer;
$data = Renderer::decode($hash);
if ($data === null) {
// Token is empty, invalid, malformed, or expired
return STATUS_ERROR;
}
$basename = $data['basename']; // e.g. person.png
$seconds = $data['expires']; // Remaining validity in seconds (0 = no expiry)Serving Resized Images
You can serve images dynamically resized using query parameters. The system adjusts width, height, quality, and aspect ratio without modifying the original file.
// /app/Controllers/Http/CdnController.php
namespace App\Controllers\Http;
use Throwable;
use Luminova\Base\Controller;
use Luminova\Attributes\Prefix;
use Luminova\Attributes\Route;
use Luminova\Storage\Renderer;
use App\Errors\Controllers\AppError;
use function Luminova\Funcs\logger;
#[Prefix(pattern: '/cdn(:root)', onError: [AppError::class, 'onAssetsError'])]
class CDNController extends Controller
{
#[Route('/cdn/assets/images/([a-zA-Z0-9-]+\.(?:png|jpg|jpeg|gif|svg|webp))', methods: ['GET'])]
public function showResizedImages(string $filename): int
{
// Read query parameters
$width = (int) $this->request->input('width', 0);
$height = (int) $this->request->input('height', 0);
$quality = (int) $this->request->input('quality', 100);
$keepRatio = (bool) $this->request->input('ratio', 1);
$expiration = 3600; // Cache time in seconds
$headers = ['Vary' => ''];
try {
$storage = Renderer::storage('images');
// Configure resizing only when a dimension is requested
if ($width > 0 || $height > 0) {
$storage->resizeImage(
$width ?: null,
$height ?: null,
$keepRatio,
$quality
);
}
// Sends the resized image if configured, otherwise streams the original file
return $storage->send($filename, $expiration, $headers)
? STATUS_SUCCESS
: STATUS_ERROR;
} catch (Throwable $e) {
logger('debug', 'Image Delivery Error: ' . $e->getMessage());
}
return STATUS_ERROR;
}
}Example URL for resizing:
https://example.com/cdn/assets/images/sample.jpg?width=300&height=200&quality=80&ratio=1How it works:
width: Target width in pixels.height: Target height in pixels.quality: Output quality from0–100. The encoding behavior depends on the image format and processing handler.ratio: Whether to preserve the original aspect ratio (1= true,0= false).- If only
widthorheightis provided, the supplied value is used for both dimensions. - If both dimensions are omitted, they default to
50 × 50pixels. - Resizing is applied only when
resizeImage()is called. When invoked without dimensions, it uses the default dimensions of50 × 50pixels. - The original file is never modified.
- Cache headers use
$expiration, allowing browsers and proxies to cache the resized response. The resized image is generated for the response and is not stored on the server. - Invalid
qualityvalues outside0–100throw anInvalidArgumentException, which can be caught and logged by the application.
Note:
Image resizing requires either the native PHP
Imagickextension, the externalPeterujah\Media\NanoImagelibrary with GD support, or a custom handler registered throughonResizeImage().
Class Definition
- Class namespace:
Luminova\Storage\Renderer - This class is marked as final and can't be subclassed
Methods
__construct
Create a file renderer for a storage directory.
public __construct(string $dirpath, bool $eTag = true, bool $weakEtag = false): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$dirpath | string | Relative path to the storage directory. |
$eTag | bool | Whether to generate ETag headers and perform validation (default: true). |
$weakEtag | bool | Whether to generate weak ETag headers, prefixed with W/ (default: false). |
Throws:
\Luminova\Exceptions\FileException - If the path is empty or only a directory separator, the directory does not exist, or the directory is not readable.
Example:
use Luminova\Storage\Renderer;
$renderer = new Renderer('/path/to/storages/images', true, false);
$renderer->send('photo.jpg', 3600);Note:
- Keep
$eTagenabled when using custom ETag headers to ensure proper cache validation.- To create an instance for application storage directory inside
/writeable/storages/, use storage().
storage
Create a file renderer for application storage directory within /writeable/storages/.
The writeable/storages/ prefix is added automatically, so only the path relative to the storage directory should be provided.
public static storage(string $basepath, bool $eTag = true, bool $weakEtag = false): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$basepath | string | Relative path within /writeable/storages/ (e.g: images/photos). |
$eTag | bool | Whether to generate ETag headers and perform validation (default: true). |
$weakEtag | bool | Whether to generate weak ETag headers (default: false). |
Return Value:
self - Returns a new configured instance of Renderer.
Throws:
\Luminova\Exceptions\FileException - If the path is empty, absolute, or contains traversal segments (. or ..), or if the storage directory does not exist or is not readable.
Example:
use Luminova\Storage\Renderer;
$response = Renderer::storage('images/photos');
$response->send(
'photo.jpg',
3600,
['X-Custom-Header' => 'Value']
);Note:
- Files must reside in the
/writeable/storages/directory.- Do not include
/writeable/storages/in the$basepathparameter; it is prepended automatically.- Backslashes in
$basepathare converted to forward slashes.- Keep
$eTagenabled when using custom ETag headers to ensure proper cache validation.
send
Sends a file to the client with proper cache and response headers.
The method accepts either a file basename or a signed file token. It resolves the file, applies cache validation (ETag / Last-Modified), sets headers, and streams the file in chunks to the client without loading its entire contents into memory. If image resizing was configured with resizeImage(), the image is processed and output instead.
public send(
string $source,
?int $expiry = null,
array $headers = [],
int $length = (1 << 21),
int $delay = 0
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$source | string | File name relative to the configured base path (e.g: image.png), or a signed file token generated by sign(). |
$expiry | int|null | Cache lifetime in seconds. Use null or 0 to disable caching (default: null). For a signed token, the remaining validity of the token is used instead. |
$headers | array<string,mixed> | Additional response headers. |
$length | int | Maximum chunk size for streaming in bytes (default: 2MB). |
$delay | int | Delay between chunks, as accepted by uwait() (default: 0). |
Return Value:
bool - Returns true if the file is streamed or a cache (304) response is handled successfully, false otherwise.
Throws:
\Luminova\Exceptions\RuntimeException - Throws if an error occurred during file processing.
Example:
use Luminova\Storage\Renderer;
$renderer = new Renderer('storages/images', true, false);
$renderer->send(
'photo.jpg',
3600,
['X-Custom-Header' => 'Value'],
1024 * 1024,
100
);Sending a signed file:
$fileHash = $renderer->sign('photo.jpg', 3600);
$renderer->send($fileHash, headers: [
'X-Custom-Header' => 'Value',
]);Sending a resized image:
$renderer->resizeImage(150, 150, true, 90);
$renderer->send('photo.jpg', headers: [
'X-Custom-Header' => 'Value',
]);Note:
- Returns
falseimmediately if$lengthis less than or equal to0, or$delayis less than0.$sourceis first resolved as a file; if no such file exists, it is decoded as a signed token (see decode()).- It automatically sends
304,404, or500responses when applicable. Error responses remove existing headers and are sent with no-cache directives. If headers were already sent, no response is changed andfalseis returned.404is sent when the file does not exist, or the signed token is invalid, malformed, or expired.500is sent when the file is empty (0bytes), cannot be opened, the content type cannot be determined, image processing fails, or streaming fails.304is only possible when the effective expiry is greater than0. It is returned when the request'sIf-None-Matchmatches the ETag (requires$eTagenabled) orIf-Modified-Sinceis not older than the file's modification time. ALast-Modifiedheader is also sent with cacheable responses.- The
Content-Typeis guessed from the file unless provided in$headers.- A
Content-Lengthprovided in$headersis used as the file size; omit it unless you need to override the detected size.- A custom
ETagin$headersis used as-is for validation and output instead of a generated one.Content-Dispositionis always set toinlineusing the file's basename as the file name.- When the effective expiry is greater than
0,Cache-Controldefaults topublic, max-age={expiry}, immutable, otherwiseno-cache, no-store, must-revalidate.ExpiresandPragmaare set accordingly unless provided in$headers.- Any active output buffers are cleared before the file is sent.
- When image resizing is configured, the image is not streamed in chunks; the processed result is output in full,
Content-LengthandETagreflect the resized output, and the resize configuration is cleared afterwards.- ETag validation for a resized image is performed against the original file's ETag, so repeat requests for resized images are validated reliably only through
If-Modified-Since.
onResizeImage
Registers a custom callback for resizing images when resizeImage() options are configured.
The callback receives the source filename, target dimensions, aspect ratio setting, output quality, and image extension. It must return the processed image content as a string, or null if resizing fails.
public function onResizeImage(callable $handler): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$handler | callable(string,int,int,bool,int,string):?string | A callback that processes the source image and returns its resized content as a string or null on failure. The callback receives the following arguments in order: |
Callback Parameters:
| Argument | Type | Description |
|---|---|---|
$filename | string | Path to the source image file. |
$width | int | Target width in pixels. |
$height | int | Target height in pixels. |
$ratio | bool | Whether to preserve the source image's aspect ratio. |
$quality | int | Requested output quality, from 0 to 100. |
$extension | string | Original image file extension used for output encoding. |
Return Value:
self - Returns the renderer instance for method chaining.
Example:
use Peterujah\Media\NanoImage;
use Luminova\Storage\Renderer;
$renderer = Renderer::storage('images');
$renderer->onResizeImage(
static function (
string $filename,
int $width,
int $height,
bool $ratio,
int $quality,
string $extension
): ?string {
$image = new NanoImage();
try {
$content = $image
->open($filename)
->blur(3)
->rotate(-90)
->resize($width, $height, $ratio)
->toString($quality);
return $content !== '' ? $content : null;
} finally {
$image->free();
}
}
);
$renderer
->resizeImage(150, 150, true, 80)
->send('photo.jpg', 3600);Note:
- The custom callback takes precedence over the built-in image processing handlers.
- The callback is invoked only when the source file is an image and
resizeImage()options have been configured for the response. - The callback must return the encoded image content as a string. Return
nullif processing fails. - Use
resizeImage()to configure the dimensions, aspect ratio, and output quality.
resizeImage
Configures image resizing options for the next image sent using send().
Sets the target dimensions, aspect ratio behavior, and output quality. If only one dimension is provided, it is used for both width and height. If neither dimension is provided, both default to 50 pixels. Each provided dimension must be a positive integer.
public function resizeImage(
?int $width = null,
?int $height = null,
bool $ratio = true,
int $quality = 100
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$width | int\|null | Target width in pixels, or null to use the height. Defaults to null. |
$height | int\|null | Target height in pixels, or null to use the width. Defaults to null. |
$ratio | bool | Whether to preserve the source image's aspect ratio. Defaults to true. |
$quality | int | Output quality from 0 to 100. Defaults to 100. The actual encoding behavior depends on the image format and processing handler. |
Return Value:
self, returns the renderer instance for method chaining.
Throws:
- \Luminova\Exceptions\InvalidArgumentException, if a provided width or height is not positive, or
$qualityis outside the range0–100.
Example:
use Luminova\Storage\Renderer;
Renderer::storage('images')
->resizeImage(800, 600, true, 80)
->send('photo.jpg', 3600);Note:
- Image processing requires either
NanoImagewithGDor the nativeImagickextension and class, unless a custom resize handler is registered usingonResizeImage().
Install NanoImage (recommended):
NanoImage is a lightweight option for image processing using PHP's GD extension.
composer require peterujah/nano-imageInstall and enable the PHP Imagick extension if you prefer to use the native Imagick handler.The image processing handler is selected automatically.
Peterujah\Media\NanoImageis used when the GD extension and NanoImage class are available. Otherwise, the nativeImagickhandler is used when the Imagick extension and class are available.
sign
Generates a signed token for a file with an optional expiration time.
The token encodes the filename, issue timestamp, expiry duration, and timezone, then encrypts the payload using Crypter.
public sign(
string $basename,
?int $expiry = 3600,
DateTimeZone|string|null $timezone = null
): string|falseParameters:
| Parameter | Type | Description |
|---|---|---|
$basename | string | The file name to sign, relative to the configured base path (e.g: filename.png). |
$expiry | int|null | Token validity duration in seconds (default: 3600 1 hour). Use null or 0 for a token without time-based expiration. |
$timezone | DateTimeZone|string|null | Optional timezone for timestamp generation. |
Return Value:
string|false - Returns the encrypted URL-safe token, or false if the file does not exist, $expiry is negative, or the timezone is invalid.
Throws:
\Luminova\Exceptions\EncryptionException - If the payload cannot be encoded or encryption fails.
Example:
use Luminova\Storage\Renderer;
$renderer = new Renderer('storages/images', true, false);
$fileHash = $renderer->sign('photo.jpg', 3600);Note:
- This method uses Luminova\Security\Encryption\Crypter for generating the signed file hash.
- The characters
+,/and=in the encrypted token are replaced with.,_and-so the hash is safe to use in a URL.- Pass the token to
send()as the$sourceto serve the file, or todecode()to inspect it.
decode
Decodes and validates a signed file token.
Decrypts the token, validates its payload and issue timestamp, and checks whether it has expired. Returns the file basename and the remaining validity duration, or null if the token is invalid or expired.
public static decode(string $hash): ?arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$hash | string | The URL-safe signed file token generated by sign(). |
Return Value:
array{basename: string, expires: int}|null - Returns the decoded file basename and the remaining validity in seconds (0 for a token without expiration), or null if the token is empty, invalid, malformed, or expired.
Example:
use Luminova\Storage\Renderer;
$renderer = Renderer::storage('images');
$fileHash = $renderer->sign('photo.jpg', 3600);
$data = Renderer::decode($fileHash);
// ['basename' => 'photo.jpg', 'expires' => 3600]Note:
- This method uses the
Crypterclass to decrypt the URL hash, after converting.,_and-back to+,/and=.- It does not check whether the file still exists.
send()calls this method internally when$sourceis not an existing file.