Luminova Framework

PHP Luminova: Private Storage File Renderer

Last updated: 2026-10-15 09:27:03

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, and Cache-Control, with support for 304 Not Modified responses.
  • Optional image resizing using the native PHP Imagick extension, the Peterujah\Media\NanoImage library, or a custom handler registered through Renderer::onResizeImage().

Luminova\Storage\Renderer provides 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.png

How 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 404 response is sent automatically and false is 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, or false if the file does not exist or $expiry is negative
  • Passing null or 0 as $expiry creates 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 404 response is sent and false is 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=1

How it works:

  • width: Target width in pixels.
  • height: Target height in pixels.
  • quality: Output quality from 0–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 width or height is provided, the supplied value is used for both dimensions.
  • If both dimensions are omitted, they default to 50 × 50 pixels.
  • Resizing is applied only when resizeImage() is called. When invoked without dimensions, it uses the default dimensions of 50 × 50 pixels.
  • 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 quality values outside 0–100 throw an InvalidArgumentException, which can be caught and logged by the application.

Note:

Image resizing requires either the native PHP Imagick extension, the external Peterujah\Media\NanoImage library with GD support, or a custom handler registered through onResizeImage().


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): mixed

Parameters:

ParameterTypeDescription
$dirpathstringRelative path to the storage directory.
$eTagboolWhether to generate ETag headers and perform validation (default: true).
$weakEtagboolWhether 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 $eTag enabled 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): self

Parameters:

ParameterTypeDescription
$basepathstringRelative path within /writeable/storages/ (e.g: images/photos).
$eTagboolWhether to generate ETag headers and perform validation (default: true).
$weakEtagboolWhether 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 $basepath parameter; it is prepended automatically.
  • Backslashes in $basepath are converted to forward slashes.
  • Keep $eTag enabled 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
): bool

Parameters:

ParameterTypeDescription
$sourcestringFile name relative to the configured base path (e.g: image.png), or a signed file token generated by sign().
$expiryint|nullCache 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.
$headersarray<string,mixed>Additional response headers.
$lengthintMaximum chunk size for streaming in bytes (default: 2MB).
$delayintDelay 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 false immediately if $length is less than or equal to 0, or $delay is less than 0.
  • $source is first resolved as a file; if no such file exists, it is decoded as a signed token (see decode()).
  • It automatically sends 304, 404, or 500 responses when applicable. Error responses remove existing headers and are sent with no-cache directives. If headers were already sent, no response is changed and false is returned.
  • 404 is sent when the file does not exist, or the signed token is invalid, malformed, or expired.
  • 500 is sent when the file is empty (0 bytes), cannot be opened, the content type cannot be determined, image processing fails, or streaming fails.
  • 304 is only possible when the effective expiry is greater than 0. It is returned when the request's If-None-Match matches the ETag (requires $eTag enabled) or If-Modified-Since is not older than the file's modification time. A Last-Modified header is also sent with cacheable responses.
  • The Content-Type is guessed from the file unless provided in $headers.
  • A Content-Length provided in $headers is used as the file size; omit it unless you need to override the detected size.
  • A custom ETag in $headers is used as-is for validation and output instead of a generated one.
  • Content-Disposition is always set to inline using the file's basename as the file name.
  • When the effective expiry is greater than 0, Cache-Control defaults to public, max-age={expiry}, immutable, otherwise no-cache, no-store, must-revalidate. Expires and Pragma are 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-Length and ETag reflect 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): self

Parameters:

ParameterTypeDescription
$handlercallable(string,int,int,bool,int,string):?stringA 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:

ArgumentTypeDescription
$filenamestringPath to the source image file.
$widthintTarget width in pixels.
$heightintTarget height in pixels.
$ratioboolWhether to preserve the source image's aspect ratio.
$qualityintRequested output quality, from 0 to 100.
$extensionstringOriginal 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 null if 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
): self

Parameters:

ParameterTypeDescription
$widthint\|nullTarget width in pixels, or null to use the height. Defaults to null.
$heightint\|nullTarget height in pixels, or null to use the width. Defaults to null.
$ratioboolWhether to preserve the source image's aspect ratio. Defaults to true.
$qualityintOutput 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:

Example:

use Luminova\Storage\Renderer;

Renderer::storage('images')
    ->resizeImage(800, 600, true, 80)
    ->send('photo.jpg', 3600);

Note:

  • Image processing requires either NanoImage with GD or the native Imagick extension and class, unless a custom resize handler is registered using onResizeImage().

Install NanoImage (recommended):

NanoImage is a lightweight option for image processing using PHP's GD extension.

composer require peterujah/nano-image

Install and enable the PHP Imagick extension if you prefer to use the native Imagick handler.The image processing handler is selected automatically. Peterujah\Media\NanoImage is used when the GD extension and NanoImage class are available. Otherwise, the native Imagick handler 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|false

Parameters:

ParameterTypeDescription
$basenamestringThe file name to sign, relative to the configured base path (e.g: filename.png).
$expiryint|nullToken validity duration in seconds (default: 3600 1 hour). Use null or 0 for a token without time-based expiration.
$timezoneDateTimeZone|string|nullOptional 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 $source to serve the file, or to decode() 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): ?array

Parameters:

ParameterTypeDescription
$hashstringThe 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 Crypter class 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 $source is not an existing file.