Skip to content

UploadedFile

Viames Marino edited this page Apr 28, 2026 · 2 revisions

Pair framework: UploadedFile

Pair\Http\UploadedFile represents one HTTP uploaded file.

It replaces the legacy Pair\Helpers\Upload helper in Pair v4 and keeps upload handling in the HTTP layer.

Factories

fromGlobals(string $fieldName): UploadedFile

Builds an object from $_FILES[$fieldName].

fromArray(array $file, ?string $fieldName = null): UploadedFile

Builds an object from one normalized $_FILES entry.

fromLocalFile(string $path, ?string $clientFilename = null, ?string $clientMediaType = null, ?string $fieldName = null): UploadedFile

Builds an object around a trusted local file for tests, CLI flows, or internal imports.

Metadata

  • fieldName(): ?string
  • clientFilename(): string
  • safeClientFilename(): string
  • temporaryPath(): string
  • size(): int
  • error(): int
  • isOk(): bool
  • errorMessage(): ?string
  • clientMediaType(): ?string
  • detectedMediaType(): ?string
  • mediaType(): ?string
  • mediaCategory(): ?string
  • extension(): ?string
  • checksum(string $algorithm = 'md5'): string

Storage

moveTo(string $directory, ?string $filename = null, bool $overwrite = false): string

Moves the upload to a local directory and returns the final path.

Behavior:

  • validates the PHP upload error before moving
  • uses move_uploaded_file() for real HTTP uploads
  • sanitizes the destination filename
  • creates missing destination folders with 0775
  • stores files with 0664
  • avoids overwriting by appending a numeric suffix unless $overwrite is true

putToS3(string $objectKey, AmazonS3 $amazonS3): void

Uploads the temporary file directly to S3 through Pair\Services\AmazonS3.

Examples

Local storage:

use Pair\Http\UploadedFile;

$upload = UploadedFile::fromGlobals('avatar');
$path = $upload->moveTo(APPLICATION_PATH . '/public/uploads');

Custom filename:

$path = $upload->moveTo(
    APPLICATION_PATH . '/public/uploads',
    'user-42-avatar.png'
);

S3 storage:

$upload->putToS3('avatars/user-42.png', $amazonS3);

Validation example:

if ('image' !== $upload->mediaCategory()) {
    throw new \RuntimeException('Avatar must be an image.');
}

Upload error handling:

$upload = UploadedFile::fromGlobals('avatar');

if (!$upload->isOk()) {
    throw new \RuntimeException($upload->errorMessage() ?? 'Upload failed.');
}

$checksum = $upload->checksum('sha256');

See also: FileMediaType, AmazonS3, File, Form.

Clone this wiki locally