Oihana PHP

UploadTrait

Provides helpers to receive PSR-7 file uploads, validate them and store them on disk.

Both helpers delegate the per-file work to the shared self::storeUploadedFile() method and throw a FileException on any failure, leaving the response shaping to the controller.

A file is checked before it takes its place : it is first moved under a provisional name (.upload-<random>.part, hidden, with no executable extension), its type is read from its content, and only then is it renamed. A refused file never carries its final name.

The stored file is named in one of three ways :

  • by default, a random name and the extension of the type read from the content (9f2c4e1a7b3d5f60a8c2e4b6d8f0a1c3.jpg) — never the name the client chose : a photo.php holding a real image would otherwise be stored, and served, as photo.php ;
  • with UploadOption::CLIENT_FILENAME, the client name cleaned by slugify(), with the extension of the detected type (Façade Nord (2).JPG → facade-nord-2.jpg) ; a name already taken is numbered (facade-nord-2-2.jpg) ;
  • with UploadOption::FILENAME, the given name, kept or refused but never altered : an extension that does not match the detected type, or a leading dot, is refused.

The extension of a type comes from UploadOption::EXTENSIONS first, then from FileMimeType::getExtension() ; a type without one (an unrecognized content) gives a name without extension. The final name is reserved in one step before the file takes it, so two uploads of the same name at the same time never overwrite each other.

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0

Table of Contents

Constants

UPLOAD_MAX_NUMBER  : int = 100
The highest number tried for a client name already taken, before a random name.
UPLOAD_MAX_STEM_LENGTH  : int = 200
The longest part before the extension kept from a client name.
UPLOAD_RANDOM_BYTES  : int = 16
The number of random bytes of a random name (twice as many hexadecimal characters).
UPLOAD_STAGING_PREFIX  : string = '.upload-'
The prefix of a provisional file : hidden, never served as code.
UPLOAD_STAGING_SUFFIX  : string = '.part'
The suffix of a provisional file : no executable extension.

Methods

receiveUpload()  : string
Receives a single uploaded file for the given field, validates it and stores it.
receiveUploads()  : array<string|int, string>
Receives multiple uploaded files for the given field, validates them and stores them.
chooseUploadExtension()  : string
Picks the extension of the stored file among the ones of its type : the client's when it is one of them, the first one otherwise, none when the type has none.
fileNameExtension()  : string
Returns the extension of a file name, with its dot and lower-case, or `''`.
mimeTypeExtensions()  : array<int, string>
Returns the extensions of a MIME type : the controller's table first, then the catalogue.
readUploadExtensions()  : array<string, string>
Reads and checks the {@see UploadOption::EXTENSIONS} table.
reserveUploadPath()  : bool
Reserves a file name in one step : creates the empty file, failing when it already exists.
storeUnderClientName()  : string
Chooses and reserves the name of a file stored under its client name.
storeUnderRandomName()  : string
Chooses and reserves a random name.
storeUploadedFile()  : string
Validates a single uploaded file and moves it into the destination directory.
uploadErrorMessage()  : string
Maps a PHP `UPLOAD_ERR_*` code to a human-readable message.

Constants

UPLOAD_MAX_NUMBER

The highest number tried for a client name already taken, before a random name.

private int UPLOAD_MAX_NUMBER = 100

UPLOAD_MAX_STEM_LENGTH

The longest part before the extension kept from a client name.

private int UPLOAD_MAX_STEM_LENGTH = 200

UPLOAD_RANDOM_BYTES

The number of random bytes of a random name (twice as many hexadecimal characters).

private int UPLOAD_RANDOM_BYTES = 16

UPLOAD_STAGING_PREFIX

The prefix of a provisional file : hidden, never served as code.

private string UPLOAD_STAGING_PREFIX = '.upload-'

UPLOAD_STAGING_SUFFIX

The suffix of a provisional file : no executable extension.

private string UPLOAD_STAGING_SUFFIX = '.part'

Methods

receiveUpload()

Receives a single uploaded file for the given field, validates it and stores it.

public receiveUpload(ServerRequestInterface $request, string $field, string $destDir[, array<string|int, mixed> $options = [] ]) : string
Parameters
$request : ServerRequestInterface

The PSR-7 request carrying the uploaded files.

$field : string

The uploaded-file field name.

$destDir : string

The destination directory.

$options : array<string|int, mixed> = []

Optional switches (see UploadOption).

Tags
throws
FileException

If the field is missing, the upload failed, the size/MIME checks fail, the name is refused, or the destination is invalid.

RandomException
Throwable
example
class AvatarController extends Controller
{
    use UploadTrait ;

    public function upload( Request $request , Response $response ) : Response
    {
        // Stored as <random>.png or <random>.jpg, outside the public web root.
        $path = $this->receiveUpload( $request , 'avatar' , '/var/uploads' , [
            UploadOption::MAX_SIZE           => 2_000_000 ,
            UploadOption::ALLOWED_MIME_TYPES => [ 'image/png' , 'image/jpeg' ] ,
        ] ) ;

        return $this->success( $request , $response , [ 'path' => $path ] ) ;
    }
}
Return values
string —

The absolute path of the stored file.

receiveUploads()

Receives multiple uploaded files for the given field, validates them and stores them.

public receiveUploads(ServerRequestInterface $request, string $field, string $destDir[, array<string|int, mixed> $options = [] ]) : array<string|int, string>

The UploadOption::FILENAME option is ignored here : one name cannot be given to several files. Each file gets its own random name, or its own cleaned client name with UploadOption::CLIENT_FILENAME — numbered when two share it.

Parameters
$request : ServerRequestInterface

The PSR-7 request carrying the uploaded files.

$field : string

The uploaded-file field name (an array of files).

$destDir : string

The destination directory.

$options : array<string|int, mixed> = []

Optional switches (see UploadOption).

Tags
throws
FileException

If the field is missing/not a list, an upload failed, the size/MIME checks fail, or the destination is invalid.

RandomException
Throwable
Return values
array<string|int, string> —

The absolute paths of the stored files.

chooseUploadExtension()

Picks the extension of the stored file among the ones of its type : the client's when it is one of them, the first one otherwise, none when the type has none.

private chooseUploadExtension(array<int, string> $extensions, string $clientExtension) : string
Parameters
$extensions : array<int, string>

The extensions of the detected type (with their dot).

$clientExtension : string

The extension of the client name (with its dot, lower-case), or ''.

Return values
string —

The extension, with its dot, or ''.

fileNameExtension()

Returns the extension of a file name, with its dot and lower-case, or `''`.

private fileNameExtension(string $name) : string
Parameters
$name : string

The file name.

Return values
string

mimeTypeExtensions()

Returns the extensions of a MIME type : the controller's table first, then the catalogue.

private mimeTypeExtensions(string|null $mimeType, array<string, string> $extensions) : array<int, string>
Parameters
$mimeType : string|null

The detected type, or null when it could not be read.

$extensions : array<string, string>

The controller's table, keys normalized.

Return values
array<int, string> —

The extensions, with their dot ; empty when none is known.

readUploadExtensions()

Reads and checks the {@see UploadOption::EXTENSIONS} table.

private readUploadExtensions(array<string|int, mixed> $options) : array<string, string>
Parameters
$options : array<string|int, mixed>

The options.

Tags
throws
FileException

When an extension is not a dot followed by letters and digits.

Return values
array<string, string> —

The table, keyed by normalized MIME type.

reserveUploadPath()

Reserves a file name in one step : creates the empty file, failing when it already exists.

private reserveUploadPath(string $path) : bool
Parameters
$path : string

The path to reserve.

Return values
bool —

True when this call created it.

storeUnderClientName()

Chooses and reserves the name of a file stored under its client name.

private storeUnderClientName(string $directory, string $clientName, array<int, string> $typeExtensions, string $clientExtension, bool $overwrite, string|null &$reserved) : string

The part before the extension is cleaned by slugify() and cut to self::UPLOAD_MAX_STEM_LENGTH characters ; nothing left gives a random name. A name already taken is numbered (-2, -3… up to self::UPLOAD_MAX_NUMBER), then a random name is used ; with $overwrite, the name is taken as it is.

Parameters
$directory : string

The destination directory, with its trailing slash.

$clientName : string

The client name, without directories.

$typeExtensions : array<int, string>

The extensions of the detected type.

$clientExtension : string

The extension of the client name, or ''.

$overwrite : bool

Whether an existing file may be replaced.

$reserved : string|null

Set to the reserved path, if any.

Tags
throws
FileException

When no name can be reserved.

RandomException
Return values
string —

The path the file will take.

storeUnderRandomName()

Chooses and reserves a random name.

private storeUnderRandomName(string $directory, string $extension, string|null &$reserved) : string
Parameters
$directory : string

The destination directory, with its trailing slash.

$extension : string

The extension, with its dot, or ''.

$reserved : string|null

Set to the reserved path.

Tags
throws
FileException

When no random name can be reserved — the directory refuses to be written.

RandomException
Return values
string —

The path the file will take.

storeUploadedFile()

Validates a single uploaded file and moves it into the destination directory.

private storeUploadedFile(UploadedFileInterface $uploaded, string $destDir[, array<string|int, mixed> $options = [] ]) : string

The file is moved under a provisional name, its type is read from its content and checked, its final name is chosen and reserved, and only then is the provisional file renamed. Any failure removes the provisional file and the reservation.

Parameters
$uploaded : UploadedFileInterface

The uploaded file.

$destDir : string

The destination directory.

$options : array<string|int, mixed> = []

Optional switches (see UploadOption).

Tags
throws
FileException

On any validation, name or destination error.

RandomException
Throwable
Return values
string —

The absolute path of the stored file.

uploadErrorMessage()

Maps a PHP `UPLOAD_ERR_*` code to a human-readable message.

private uploadErrorMessage(int $error) : string
Parameters
$error : int

One of the UPLOAD_ERR_* constants.

Return values
string —

The associated message.

On this page

Search results