Skip to content

CkFile

Job: make file names and paths from the outside world safe to use — clean the name, read the extension, guard the path, decode base64 uploads — and keep the files themselves, inside a named place and never at a path.

Files reach an application as text: a name typed into a form, a path stored in a database, an upload sent as base64. None of that text can be trusted as-is. CkFile splits the work in two: FileName is a sanitizer — it repairs a name until it is safe to save; RelativePath is a gate — a suspicious path is rejected outright, never repaired. The standard rejection values apply: a string method answers '' (empty), FromBase64 answers an empty string — no bytes — and HasExtension answers false. Nothing throws unless you ask (How it works), and the readers touch no disk: every one works on the text of a name or a path, so a value can be judged before a folder exists and against the rules of every operating system at once. A value that is not text at all — a number, a boolean, an array — is refused as "not a file name", "not a path" and the like, by the kind of thing it was.

The files themselves live in a FilePlace, never at a path: Write, Read, Copy, Move, Delete, Exists, Size, Files and FullPath take a place and a relative path, hold the path to the gate inside the place's folder, and never reach a folder the application has not named. Each place takes only the extensions it was given, never a blocked one, only a file within its limit, and only content that proves its extension — a PNG named scan.pdf is refused as such. Where the places live is said once, in CkSettings::FilePlatform: a platform's own folders, or one root of your application's own. As shipped nothing is set, so nothing can touch a disk until you have said where your files live — Setting up your file places is the walk-through.

Bytes are a PHP binary string: FromBase64 answers one and ToDataUri takes one, and neither is cleaned, composed or measured as text — an empty string is how "no bytes" comes back, never a null.

Quick look

use SafeCoder\CommonKit\CkFile;
use SafeCoder\CommonKit\Enums\FilePlace;

CkFile::FileName('Report: Q3?.pdf');                       // -> 'Report_ Q3_.pdf'
CkFile::Extension('archive.tar.gz');                       // -> 'gz'
CkFile::RelativePath('a/../secrets.txt');                  // -> ''  (a climb — rejected)
CkFile::FromBase64('AQID');                                // -> "\x01\x02\x03"  (three bytes)
CkFile::DataUriType('data:image/PNG;base64,iVBORw0KGgo');  // -> 'image/png'
CkFile::IsRelativePath('a/../secrets.txt');                // -> false
CkFile::InMediaTypes(
    input: 'data:image/png;base64,iVBORw0KGgo',
    types: 'image/*'
);   // -> true  (for any image)
CkFile::IsWithinSize(
    input: 'data:image/png;base64,iVBORw0KGgo',
    maxBytes: 5 * 1024 * 1024
);   // -> true  (when 5 MB or less)
CkFile::Combine(
    root: '/srv/uploads',
    relative: '../secrets.txt'
);   // -> ''  (the join escapes the root)
CkFile::SizeToString(1536);                 // -> '1.5 KB'
CkFile::Explain('a/../b');                  // -> 'it climbs out of its folder (..)'
CkFile::SniffType(hex2bin('89504E470D0A1A0A0000000D49484452'));   // -> 'image/png'   (the bytes, whatever the name)
CkFile::IsOfType("id,name\n1,Mary\n", 'csv');                    // -> true
CkFile::ExtensionFor('image/jpeg');                              // -> 'jpg'
CkFile::MaxBytes(FilePlace::Images);                             // -> 2097152   (as shipped)
// no-check
use SafeCoder\CommonKit\CkFile;
use SafeCoder\CommonKit\Enums\FilePlace;

CkFile::Write(FilePlace::Documents, 'claim-18/scan.pdf', $bytes);   // true once the file is in place, false when a rule refuses it
CkFile::Read(FilePlace::Documents, 'claim-18/scan.pdf');            // the bytes, or '' for no file
CkFile::Exists(FilePlace::Documents, 'claim-18/scan.pdf');          // true
CkFile::Move(FilePlace::Uploads, 'in/7f3a.pdf', 'claim-18/scan.pdf', into: FilePlace::Documents);
CkFile::Delete(FilePlace::Temporary, 'in/7f3a.pdf');                // true once nothing is there
CkFile::FullPath(FilePlace::Documents, 'claim-18/scan.pdf');        // the full path, for readfile() or a framework's own storage

Your file places, set once

A place is a kind of file, never a path: every file operation below takes a FilePlace — Images, Documents, Uploads — and a relative path, and never a full one. Where the places live is said once, in CkSettings::FilePlatform:

Place Joomla! (JPATH_ROOT) Laravel (storage_path('app')) WordPress (wp_upload_dir()) Custom (your root)
Images images/ public/images/ uploads/images/ Images/
Media images/ public/media/ uploads/media/ Media/
Videos images/videos/ public/videos/ uploads/videos/ Videos/
Audio images/audio/ public/audio/ uploads/audio/ Audio/
Documents documents/ documents/ uploads/documents/ Documents/
Uploads uploads/ uploads/ uploads/uploads/ Uploads/
Temporary tmp/ temporary/ uploads/temporary/ Temporary/
Imports imports/ imports/ uploads/imports/ Imports/
Exports exports/ exports/ uploads/exports/ Exports/
Archives archives/ archives/ uploads/archives/ Archives/

On a platform the library knows, there is nothing to configure: the folders are found through the platform's own constant or function, the platform's base — images/, storage/app, the uploads folder — must exist, and the place's folder below it is made the first time something is written there. A platform that has not loaded yet refuses every operation with a reason that names what is missing: "the platform's root is not available (JPATH_ROOT is not defined)".

With FilePlatform::Custom, as shipped, your application says one root, and every place is the subfolder named after it — /var/app/files/Images, /var/app/files/Documents — made when first written to. Three doors set it, a later one winning:

  1. In code, CkSettings::DefaultFileRoot for the root, and per place CkSettings::FileRoot($place) for a folder of its own, CkSettings::FileExtensions($place) and CkSettings::FileMaxBytes($place): a match each, every case null as shipped. Fill one in with a literal, or with anything PHP can answer.
  2. In a variable — CommonKit__Files__Root, and per place CommonKit__Files__Documents__Root, __MaxBytes, __Extensions (comma-separated), and CommonKit__Files__Blocked — read from $_ENV, $_SERVER and the process environment, which is where a .env file lands:

    CommonKit__Files__Root=/var/app/files
    CommonKit__Files__Documents__MaxBytes=10485760
    CommonKit__Files__Documents__Extensions=pdf,docx,csv
    CommonKit__Files__Archives__Root=/mnt/archive
    CommonKit__Files__Blocked=rar,7z
    

A per-place folder — FileRoot or its variable — wins on every platform, so one place can live elsewhere while the rest follow the platform. The library reads the variables itself, once, the first time a file operation runs; a change needs a new request to be seen.

As shipped, no platform is named and no root is set, so nothing can touch a disk until you have said where your files live; every place takes 2 MB (CkSettings::DefaultMaxFileBytes), and the extensions it takes are the library's own:

Place Takes by default
Images jpg, jpeg, png, gif, webp, bmp, tif, tiff, heic, avif
Videos mp4, mov, webm, mkv, avi
Audio mp3, wav, ogg, m4a, flac
Media pictures, video and audio together
Documents pdf, doc, docx, xls, xlsx, ppt, pptx, odt, ods, odp, rtf, txt, csv
Imports csv, xlsx, xls, json, xml, txt
Exports pdf, csv, xlsx, docx, json, zip
Archives zip, 7z, rar, gz, tar
Uploads, Temporary all of the above

No place takes "anything", and svg is out of Images on purpose: it is XML that can carry a script. AllowedExtensions and MaxBytes answer the rules in force, for an upload form's accept attribute and its size hint.

Four rules stand whatever you set:

  • A root that is a root is refused as if it were unset — the file system's root, a drive, the application's own folder (the document root, or the running script's folder) or one above it — and so is a place's own folder, so a place is always a folder of its own and ../configuration.php is never in bounds. The root, a place's own folder or the platform's base must exist; the folders below, the library makes as needed. A file is always inside a place, never the place: a path that names the folder itself is refused, and so is one that climbs out, exactly as RelativePath refuses it.
  • Blocked extensions are never taken, however a place is listed. CkSettings::BlockedExtensions names them, each with what it is — programs, the scripts a system or a web server runs, the pages and scripts a browser runs, a web server's own files — and a refusal says so: a blocked extension (php, a script the web server runs). A blocked extension is refused anywhere in a name, since Apache runs shell.php.pdf as PHP by its first extension, and so is a longer extension whose first three characters are blocked, since a Windows short name keeps only those: shell.phpx is SHELL~1.PHP. The variable can add to that list, never take from it; BlockedExtensions lists the ones in force.
  • A link below a place is never followed, in or out. A symbolic link planted inside a place's folder — by an archive extracted there, by another account on a shared host — would make the text of a path lie, so every operation refuses one wherever it stands between the place's folder and the file: a link inside the place (linkdir), which is never followed. The place's own folder may be a link.
  • A page is taken nowhere, under any name. Content a browser would run — HTML, an XHTML-namespaced or stylesheet-bearing XML, an SVG — is refused even under an extension you listed that the library has no type for, since a file served without a type is sniffed by the browser. An extension you list is otherwise taken on your word, and xml or xsl, which browsers render, should not be among them for a folder the web server serves.

Methods

FileName

A name that is safe to save.

static function FileName(
    mixed $input = null,
    mixed $fallback = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string
Parameter Type Default What it does
input mixed null The raw value: text, or an object that writes itself as text. Anything else is refused.
fallback mixed null Value to use when nothing usable survives. It goes through the same sanitizing and is never returned as typed; a fallback that is itself rejected answers ''.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering '', when neither the value nor the fallback can be used.

Returns

When Default With throwIfInvalid: true
The value (or the fallback) survives the sanitizing The safe name: 'Report_ Q3_.pdf' The safe name: 'Report_ Q3_.pdf'
Rejected: missing, over CkSettings::MaxPathInputLength (1,024) characters, not text, or nothing survives the sanitizing Empty string Throws CkFileException — carries Input, Expected and Reason

A sanitizer, not a validator — use RelativePath when the value claims to be a path.

Turns whatever arrives into a name any operating system will accept. The characters Windows forbids (< > : " / \ | ? *) become underscores, trailing dots and spaces go, and a name longer than 255 characters (CkSettings::MaxFileNameLength) is cut with its extension kept — never through the middle of a character, which no filesystem takes. Windows also reserves some device names — CON, PRN, NUL, COM1 and friends — that hang or misbehave when used as a file name, even with an extension; those are defused with a leading underscore. This is a rename, not a rejection: the goal is a name you can write to disk.

use SafeCoder\CommonKit\CkFile;

CkFile::FileName('Report: Q3?.pdf');     // -> 'Report_ Q3_.pdf'
CkFile::FileName('CON.txt');             // -> '_CON.txt'  (reserved name defused)
CkFile::FileName('invoice/2026.pdf');    // -> 'invoice_2026.pdf'  (a slash is not a name)
CkFile::FileName('...');                 // -> ''  (nothing survives — rejected)

Extension

What kind of file the name claims.

static function Extension(
    mixed $input = null,
    mixed $fallback = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string
Parameter Type Default What it does
input mixed null The raw file name or path.
fallback mixed null A file name to use when the value has no usable extension. It goes through the same reading and is never returned as typed; a fallback that is itself rejected answers ''.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering '', when neither the value nor the fallback has a usable extension.

Returns

When Default With throwIfInvalid: true
The value (or the fallback) has a usable extension The extension, lower-case and without the dot: 'pdf' The extension, lower-case and without the dot: 'pdf'
Rejected: missing, oversized, no dot, a dotfile, or an extension that is not letters and digits Empty string Throws CkFileException — carries Input, Expected and Reason

With throwIfInvalid: true a dotfile throws too — no extension counts as a rejection here.

The extension of a file name or path — lower-case, without the dot, letters and digits only. A path answers its last segment's extension; only the last extension counts. A dotfile (a name starting with a dot, like .gitignore) and a name without a dot have no extension and answer ''.

use SafeCoder\CommonKit\CkFile;

CkFile::Extension('Report.PDF');                // -> 'pdf'
CkFile::Extension('archive.tar.gz');            // -> 'gz'  (only the last)
CkFile::Extension('exports/2026/report.pdf');   // -> 'pdf'
CkFile::Extension('.gitignore');                // -> ''  (a dotfile has no extension)

HasExtension

The allow-list check.

static function HasExtension(
    mixed $input = null,
    mixed ...$allowed
): bool
Parameter Type Default What it does
input mixed null The raw file name or path.
allowed mixed ... (empty) The extensions to accept — each argument an extension, or a list of extensions — compared without case or dots; null, empty and blank entries are skipped.

Returns

When You get
The name's extension matches an entry on the list true
No extension, an empty list, or no match false — and it never throws

No throwIfInvalid here (a variadic list must come last) — call Extension with it first when you need the error.

True when the name's extension is on your list. Entries are compared without case or dots, so 'pdf', '.PDF' and 'Pdf' all mean the same thing. A name without an extension, or an empty list, answers false.

use SafeCoder\CommonKit\CkFile;

CkFile::HasExtension(
    input: 'Report.PDF',
    allowed: ['pdf', 'docx']
);   // -> true

CkFile::HasExtension(
    input: 'photo.exe',
    allowed: ['pdf', 'docx']
);   // -> false

CkFile::HasExtension(
    input: 'scan.pdf',
    allowed: ['.PDF']
);   // -> true  (dots and casing in entries are forgiven)

RelativePath

The path-traversal gate.

static function RelativePath(
    mixed $input = null,
    mixed $fallback = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string
Parameter Type Default What it does
input mixed null The raw path.
fallback mixed null A path to use when the value cannot be used. It goes through the same validation and is never returned as typed; a fallback that is itself rejected answers ''.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering '', when neither the value nor the fallback can be used.

Returns

When Default With throwIfInvalid: true
The value (or the fallback) stays inside its folder The tidied path, forward slashes only: 'exports/2026/report.pdf' The tidied path, forward slashes only: 'exports/2026/report.pdf'
Rejected: missing, oversized, rooted, a drive or stream colon, a .. climb, a forbidden character, a segment starting with a space or ending in a dot or space, or a reserved Windows name in a segment Empty string Throws CkFileException — carries Input, Expected and Reason

Rejection over repair — a "fixed" hostile path is still hostile intent.

Validates a relative path you stored or received — 'exports/2026/report.pdf' — as one that stays inside its folder. Path traversal is the classic attack where a stored path uses '..' (which means "the folder above") to climb out of the folder you meant and reach files like system secrets. So this method rejects instead of repairing: a rooted path (one starting with /), a drive or stream colon (C:), a '..' climb, a forbidden character, a segment starting with a space or ending in a dot or space, or a reserved Windows name in any segment rejects the whole value. What passes is tidied — backslashes become forward slashes, '.' segments and doubled slashes collapse. Join the result with your own base folder through Combine; never accept an absolute path from data.

use SafeCoder\CommonKit\CkFile;

CkFile::RelativePath('exports\\2026\\report.pdf');   // -> 'exports/2026/report.pdf'
CkFile::RelativePath('./a/./b.txt');                 // -> 'a/b.txt'
CkFile::RelativePath('a/../secrets.txt');            // -> ''  (a climb — rejected)
CkFile::RelativePath('/etc/passwd');                 // -> ''  (rooted — rejected)
CkFile::RelativePath('C:\\temp\\x.txt');             // -> ''  (drive colon — rejected)

FromBase64

Text back into bytes.

static function FromBase64(
    mixed $input = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string
Parameter Type Default What it does
input mixed null The base64 text, or a data URI holding one.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering no bytes, when the value cannot be decoded.

Returns

When Default With throwIfInvalid: true
The text decodes The bytes, as a binary string: "\x01\x02\x03" The bytes, as a binary string: "\x01\x02\x03"
Rejected: missing, over CkSettings::MaxBase64InputLength (16,777,216) characters, a data URI without a base64 payload, an empty payload, or not valid base64 Empty string — no bytes, never null Throws CkFileException — carries Input, Expected and Reason

The declared media type of a data URI reads separately with DataUriType.

Decodes base64 text into bytes. Base64 is the standard way of writing bytes as plain text — it is how file uploads travel inside JSON. This method reads plain base64, the URL-safe alphabet (- and _ instead of + and /), unpadded text (missing = signs at the end), and a full data URI like 'data:image/png;base64,…' (the payload after the comma). Whitespace inside is ignored. The answer is never null: an empty string means the value was rejected — so "bytes came back" means it really decoded. What counts as base64 is what IsBase64 counts: text whose last character carries bits no byte can hold — 'no', 'US', a date — is refused, not read as the bytes a lenient decoder would invent for it.

The answer is bytes, not text: a binary string, valid UTF-8 only if the file happened to be. Never hand it to a text method, and never write it into a place that expects text without encoding it first — strlen() counts its bytes, bin2hex() shows them.

use SafeCoder\CommonKit\CkFile;

CkFile::FromBase64('AQID');                          // -> "\x01\x02\x03"
CkFile::FromBase64('data:image/png;base64,AQID');    // -> "\x01\x02\x03"
CkFile::FromBase64('AQ');                            // -> "\x01"  (unpadded is fine)
CkFile::FromBase64('SGVsbG8');                       // -> 'Hello'  (five bytes that happen to be text)
CkFile::FromBase64('not base64!');                   // -> ''  (no bytes — rejected)
CkFile::FromBase64('2026-08-31');                    // -> ''  (not base64, whatever a lenient decoder makes of it)

DataUriType

What a data URI says it is.

static function DataUriType(
    mixed $input = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string
Parameter Type Default What it does
input mixed null The data URI.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering '', when the value cannot be used.

Returns

When Default With throwIfInvalid: true
The data URI declares a well-formed media type The lowercase type: 'image/png' The lowercase type: 'image/png'
Rejected: missing, not a data URI, or no well-formed media type in it Empty string Throws CkFileException — carries Input, Expected and Reason

Shape-checked, not verified — the type is what the sender claimed, not what the bytes are.

The media type a data URI declares — the label that says what kind of file it is, like 'image/png' — lowercased. The type is shape-checked: one name, one slash, letters, digits and .+- only, so a stored value cannot smuggle markup into a Content-Type header. Empty means the value is missing, is not a data URI, or declares no well-formed type. Note the declared type is only a claim — it tells you what the sender said, not what the bytes really are.

use SafeCoder\CommonKit\CkFile;

CkFile::DataUriType('data:image/PNG;base64,iVBORw0KGgo');   // -> 'image/png'
CkFile::DataUriType('data:;base64,AAAA');                   // -> ''  (no type declared)
CkFile::DataUriType('just text');                           // -> ''

IsSafeFileName

Already a name FileName would leave alone?

static function IsSafeFileName(
    mixed $input = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): bool
Parameter Type Default What it does
input mixed null The raw file name.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering false, when the value is not a safe name as written.

Returns

When Default With throwIfInvalid: true
The cleaned value equals what FileName would make of it true true
FileName would have to change it — a forbidden character, a reserved name, a trailing dot, over-long false Throws — the reason says what it would become
An invisible character in the name — a zero-width space, a soft hyphen, a bidi mark, a control character false Throws — "an invisible character in the name: FileName would remove it"
Rejected: nothing usable at all false Throws CkFileException — carries Input, Expected and Reason

A shape check for intake policies that reject rather than repair. Surrounding whitespace and markup are cleaned away first, as every shape check does; then the name must be exactly what FileName would produce. 'who?.pdf' is false, and with the flag the reason reads FileName would change it to "who_.pdf". An invisible character is the one thing the cleaning is not allowed to excuse: "re\u{200B}port.pdf" cleans to 'report.pdf' and looks like it, but it is a different name and a different file, so it is false — the name as written is what is judged.

use SafeCoder\CommonKit\CkFile;

CkFile::IsSafeFileName('Report Q3.pdf');        // -> true
CkFile::IsSafeFileName('who?.pdf');             // -> false
CkFile::IsSafeFileName('con.txt');              // -> false  (a reserved name)
CkFile::IsSafeFileName("re\u{200B}port.pdf");   // -> false  (a zero-width space inside)

IsRelativePath

Does it pass the traversal gate?

static function IsRelativePath(
    mixed $input = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): bool
Parameter Type Default What it does
input mixed null The raw path.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering false, when the value is not a safe relative path.

Returns

When Default With throwIfInvalid: true
Relative, no drive or stream colon, no .. climb, no forbidden character, no reserved segment true true
Rejected: any of those false Throws CkFileException — carries Input, Expected and Reason

The yes-or-no form of RelativePath, for validation code; call the gate itself when you want the normalized path back. A bare file name is a relative path.

use SafeCoder\CommonKit\CkFile;

CkFile::IsRelativePath('exports/2026/report.pdf');   // -> true
CkFile::IsRelativePath('a/../secrets.txt');           // -> false  (a climb)
CkFile::IsRelativePath('/etc/passwd');                // -> false  (rooted)

IsBase64

Does the text decode?

static function IsBase64(
    mixed $input = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): bool
Parameter Type Default What it does
input mixed null The base64 text or data URI.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering false, when the value is not base64.

Returns

When Default With throwIfInvalid: true
Plain, URL-safe or unpadded base64, or a data URI with a base64 payload, decoding to at least one byte true true
Rejected: not base64, an empty payload, a data URI without base64, over the cap false Throws CkFileException — carries Input, Expected and Reason

The yes-or-no form of FromBase64, judged without building the bytes: the same shaping — whitespace ignored, the URL-safe alphabet mapped, padding restored — then the library's own validity check, which is strict where PHP's built-in decoder is lenient. An empty payload is not a file, so it is false.

use SafeCoder\CommonKit\CkFile;

CkFile::IsBase64('SGVsbG8');                  // -> true   (unpadded is fine)
CkFile::IsBase64('data:text/plain,hello');    // -> false  (no base64 payload)
CkFile::IsBase64('AAAAA');                    // -> false  (a length no base64 has)

IsDataUri

A data URI with a file in it?

static function IsDataUri(
    mixed $input = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): bool
Parameter Type Default What it does
input mixed null The raw value.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering false, when the value is not such a data URI.

Returns

When Default With throwIfInvalid: true
The data: prefix, a well-shaped media type, ;base64, and a payload that decodes to at least one byte true true
Rejected: not a data URI, no type, no base64, an empty or invalid payload false Throws CkFileException — carries Input, Expected and Reason — the reason says which

Everything an upload field should carry, in one check. A plain-text data URI (data:text/plain,hello) is false, as FromBase64 treats it. The type is shape-checked, not verified against the bytes; see InMediaTypes to allow-list it.

use SafeCoder\CommonKit\CkFile;

CkFile::IsDataUri('data:image/png;base64,iVBORw0KGgo');   // -> true
CkFile::IsDataUri('data:;base64,AQID');                   // -> false  (no type)
CkFile::IsDataUri('data:image/png;base64,');              // -> false  (an empty payload)

InMediaTypes

One of the types we accept?

static function InMediaTypes(
    mixed $input = null,
    mixed ...$types
): bool
Parameter Type Default What it does
input mixed null The data URI.
types mixed ... (empty) The media types to accept — each argument a type, or a list of types: type/subtype, type/* for a family, or */* for anything that has a type. Null, empty and blank entries are skipped.

Returns

When You get
The value is a data URI whose declared type matches an entry true
It is not a data URI, declares no well-formed type, no entry matches, or the list is empty false — an answer, not a failure; it never throws

The upload allow-list check, "images only". The declared type is read the way DataUriType reads it, lowercase, and entries are compared the same way. This judges the declared type alone — a well-shaped lie passes — so pair it with IsDataUri for the payload and check the bytes when it matters. A variadic list must be last, so there is no throwIfInvalid; call DataUriType with it first.

use SafeCoder\CommonKit\CkFile;

CkFile::InMediaTypes(
    input: 'data:image/png;base64,iVBORw0KGgo',
    types: ['image/png', 'image/jpeg']
);   // -> true  (a PNG)

CkFile::InMediaTypes(
    input: 'data:image/png;base64,iVBORw0KGgo',
    types: 'image/*'
);   // -> true  (any image type)

CkFile::InMediaTypes(
    input: 'data:application/pdf;base64,JVBERi0xLjQ',
    types: 'image/*'
);   // -> false

IsWithinSize

Small enough to accept?

static function IsWithinSize(
    mixed $input = null,
    int $maxBytes = 0,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): bool
Parameter Type Default What it does
input mixed null The base64 text or data URI.
maxBytes int 0 The largest decoded size allowed, in bytes. Below 0 acts as 0.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering false, when the value is not base64.

Returns

When Default With throwIfInvalid: true
Valid base64 that decodes to no more than maxBytes true true
Valid base64 that decodes to more false false
Rejected: not base64 false Throws CkFileException — carries Input, Expected and Reason

The "uploads up to 5 MB" rule, worked out from the text alone: base64 length maps to byte count exactly once padding is accounted for, so nothing is decoded and the check is cheap enough to run before anything is. Too big is an answer, not an error.

use SafeCoder\CommonKit\CkFile;

CkFile::IsWithinSize(
    input: 'data:image/png;base64,iVBORw0KGgo',
    maxBytes: 5 * 1024 * 1024
);   // -> true  (the file is 5 MB or less)

CkFile::IsWithinSize(
    input: 'AQID',
    maxBytes: 2
);   // -> false  (three bytes)

Combine

A full path that cannot escape its folder.

static function Combine(
    mixed $root = null,
    mixed $relative = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string
Parameter Type Default What it does
root mixed null The folder everything must stay inside.
relative mixed null The stored or received relative path.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering '', when the root is missing, the relative path fails the gate, or the join escapes the root.

Returns

When Default With throwIfInvalid: true
The relative path passes RelativePath's gate and the join stays inside the root The full path, in the operating system's separators The path
Rejected: no root, a path the gate refuses, a join that escapes '' Throws CkFileException — carries Input, Expected and Reason

The traversal-safe form of a plain join, which happily follows '../' out of the folder. The gate runs first, then the joined path is resolved — on the text alone, the disk is never asked — and checked to start inside the root, so no spelling escapes.

use SafeCoder\CommonKit\CkFile;

CkFile::Combine(
    root: '/srv/uploads',
    relative: '2026/report.pdf'
);   // -> '/srv/uploads/2026/report.pdf'

CkFile::Combine(
    root: '/srv/uploads',
    relative: '../secrets.txt'
);   // -> ''

SizeToString

1.5 MB, as people read it.

static function SizeToString(
    mixed $bytes = null,
    int $decimals = 1,
    string $fallback = '',
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string
Parameter Type Default What it does
bytes mixed null The byte count: a number, or text — read the way CkNumber::Int reads one.
decimals int 1 The most decimal places to show, 0 to 3.
fallback string '' What comes back when the count cannot be read.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering the fallback, when the count is not a whole, non-negative number.

Returns

When Default With throwIfInvalid: true
A whole, non-negative count '512 B', '1.5 KB', '1 MB' — steps of 1024, halves rounded up, trailing zeros dropped The size
Rejected: negative, a fraction, junk The fallback Throws CkFileException — carries Input, Expected and Reason

The convention operating systems and browsers show.

use SafeCoder\CommonKit\CkFile;

CkFile::SizeToString(1536);       // -> '1.5 KB'
CkFile::SizeToString(5242880);    // -> '5 MB'
CkFile::SizeToString('1536');     // -> '1.5 KB'  (a count that arrived as text)

MediaType

The Content-Type a file name implies.

static function MediaType(
    mixed $input = null,
    mixed $fallback = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string
Parameter Type Default What it does
input mixed null The raw file name or path.
fallback mixed null The media type to answer for an unknown extension; 'application/octet-stream' is the usual choice. Held to the bare type/subtype shape: parameters reject it rather than being dropped.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering '', when no media type can be answered.

Returns

When Default With throwIfInvalid: true
The extension is in the table The media type, lowercase: 'application/pdf' The type
It is not, and a well-formed fallback is given The fallback The fallback
Rejected: no extension, an unknown one with no fallback, a fallback that is not a media type '' Throws CkFileException — carries Input, Expected and Reason

A fixed table of the common document, image, audio, video, archive, font and web formats, read the way Extension reads the extension.

use SafeCoder\CommonKit\CkFile;

CkFile::MediaType('Report.PDF');   // -> 'application/pdf'

CkFile::MediaType(
    input: 'data.xyz',
    fallback: 'application/octet-stream'
);   // -> 'application/octet-stream'

ToDataUri

Bytes as a data URI.

static function ToDataUri(
    mixed $bytes = null,
    mixed $type = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string
Parameter Type Default What it does
bytes mixed null The file bytes, as a binary string — taken as they stand, never cleaned.
type mixed null The media type, e.g. 'image/png', bare — no parameters — see MediaType.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering '', when there are no bytes or the type is not well-formed.

Returns

When Default With throwIfInvalid: true
Bytes and a well-formed type 'data:image/png;base64,…' The URI
Rejected: no bytes, a malformed type '' Throws CkFileException — carries Input, Expected and Reason

The reverse of FromBase64, for embedding a file in JSON, HTML or a mail. Every one of the 256 byte values survives the trip out and back.

use SafeCoder\CommonKit\CkFile;

CkFile::ToDataUri(
    bytes: "\x89PNG\r\n\x1a\n",
    type: CkFile::MediaType('photo.png')
);   // -> 'data:image/png;base64,iVBORw0KGgo='

FullPath

The full path of a relative path inside a place.

static function FullPath(
    FilePlace $place = FilePlace::Uploads,
    mixed $relative = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string
Parameter Type Default What it does
place FilePlace FilePlace::Uploads The place the path is inside.
relative mixed null The relative path.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering '', when the place has no folder or the path fails the gate.

Returns

When Default With throwIfInvalid: true
The place has a folder, the path passes RelativePath's gate and resolves inside it The full path, in the operating system's form The path
Rejected: no folder for the place, a path the gate refuses, the folder itself '' Throws CkFileException — carries Input, Expected and Reason

Combine for a named place. Nothing is read or written and the file need not exist: this is the path to hand to something else that reads or writes the file — readfile(), a framework's own storage, a response that streams a file.

// no-check
use SafeCoder\CommonKit\CkFile;
use SafeCoder\CommonKit\Enums\FilePlace;

CkFile::FullPath(FilePlace::Images, '2026/logo.png');       // '/var/app/files/Images/2026/logo.png' with a custom root
CkFile::FullPath(FilePlace::Images, '../configuration.php');   // -> ''  (the gate)
CkFile::FullPath(FilePlace::Videos, 'clip.mp4');            // -> ''  while no folder is set for Videos

Exists

Whether a file is there.

static function Exists(
    FilePlace $place = FilePlace::Uploads,
    mixed $relative = null
): bool

Returns true for a file at the relative path inside the place; false for a folder, for nothing there, for a path the gate refuses and for a place with no folder. A validator: it never throws.

// no-check
CkFile::Exists(FilePlace::Documents, '2026/claim-18/scan.pdf');   // true when the file is there
CkFile::Exists(FilePlace::Documents, '2026/claim-18');            // false: a folder
CkFile::Exists(FilePlace::Documents, '../configuration.php');     // false: the gate refuses ".."

Size

A file's size in bytes.

static function Size(
    FilePlace $place = FilePlace::Uploads,
    mixed $relative = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): int

Returns the size in bytes, or 0 when there is no such file, the path names a folder, the gate refuses it, or the place has no folder; with throwIfInvalid: true a CkFileException says which. An empty file is 0 too; SizeOrNull tells the two apart, and SizeToString writes the number for people.

SizeOrNull

A file's size, or null for no file.

static function SizeOrNull(
    FilePlace $place = FilePlace::Uploads,
    mixed $relative = null
): ?int

Returns the size in bytes, or null when there is no such file, the path names a folder, the gate refuses it, or the place has no folder — so an empty file, which is 0, is told from a missing one. Never throws.

Files

The files in a place, or in a folder of it.

static function Files(
    FilePlace $place = FilePlace::Uploads,
    mixed $folder = null
): array
Parameter Type Default What it does
place FilePlace FilePlace::Uploads The place.
folder mixed null The relative path of a subfolder; null, '' or '.' for the place itself.

Returns the files' relative paths from the place's folder, forward slashes, sorted — files only, no folders or symbolic links, and never a write in progress. Empty when the place has no folder, or the subfolder is refused by the gate or is not there. Never throws.

// no-check
CkFile::Files(FilePlace::Documents, 'claim-18');   // ['claim-18/scan-3f9a1c7e.pdf', 'claim-18/scan-7b2d0e41.pdf']

Read

A file's bytes.

static function Read(
    FilePlace $place = FilePlace::Uploads,
    mixed $relative = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string

Returns the file's bytes as a binary string, or '' when there is no such file, the path names a folder, the gate refuses it, or the place has no folder; with throwIfInvalid: true a CkFileException says which. An empty file reads as '' too; ReadOrNull tells the two apart. The file is read whole, so one over the place's limit (MaxBytes) is refused rather than loaded — "over 2097152 bytes" — a large file is served through FullPath and a stream.

// no-check
$scan = CkFile::Read(FilePlace::Documents, '2026/claim-18/scan.pdf');   // the bytes
CkFile::Read(FilePlace::Documents, 'missing.pdf');                       // -> ''  (nothing there)

ReadOrNull

A file's bytes, or null for no file.

static function ReadOrNull(
    FilePlace $place = FilePlace::Uploads,
    mixed $relative = null
): ?string

Returns the bytes, or null when there is no such file, the path names a folder, the gate refuses it, the place has no folder, or the file is over the place's limit — so an empty file, which reads as '', is told from a missing one. Never throws.

Write

Bytes to a file inside a place.

static function Write(
    FilePlace $place = FilePlace::Uploads,
    mixed $relative = null,
    mixed $bytes = null,
    bool $overwrite = false,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): bool
Parameter Type Default What it does
place FilePlace FilePlace::Uploads The place to write in.
relative mixed null The relative path of the file.
bytes mixed null The file's content, a binary string.
overwrite bool false true to replace an existing file; false to refuse one.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering false, when the file could not be written.

Returns true once the file is in place, false when it could not be written; with throwIfInvalid: true the exception's Reason says which rule refused it.

The way a payload's base64 lands on disk: FromBase64, then this. The path is held to RelativePath's gate and resolved inside the place's folder, the file's folders are created when missing, and the bytes are written beside the destination under a temporary name and published into place once complete, so the path never names a half-written file. With overwrite: false, a competing file is refused even if it appears while the operation is running. On a filesystem that cannot make a hard link, the file is renamed into place after a fresh look instead, which leaves a window of microseconds in which a competing file could still be replaced. The place's rules are applied: the extension must be one the place takes and never a blocked one, the bytes within the place's limit, and the content must prove the extension — a PNG named scan.pdf is refused as such, and so is an empty file, which proves nothing. A staged upload is named with the extension it claims, 7f3a.pdf, so it is checked once, on arrival.

// no-check
$scan = CkFile::FromBase64($payload['scan']);

CkFile::Write(FilePlace::Documents, '2026/claim-18/scan.pdf', $scan);                    // true: written
CkFile::Write(FilePlace::Documents, '2026/claim-18/scan.pdf', $scan);                    // false: already there
CkFile::Write(FilePlace::Documents, '2026/claim-18/scan.pdf', $scan, overwrite: true);   // true: replaced
CkFile::Write(FilePlace::Documents, '2026/claim-18/shell.php', $scan);                   // false: a blocked extension
CkFile::Write(FilePlace::Images, 'avatar.png', $scan);                                   // false: the content is a PDF

Copy

A copy of a file, judged like a write.

static function Copy(
    FilePlace $place = FilePlace::Uploads,
    mixed $from = null,
    mixed $to = null,
    bool $overwrite = false,
    ?FilePlace $into = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): bool
Parameter Type Default What it does
place FilePlace FilePlace::Uploads The place the source is in.
from mixed null The relative path of the source.
to mixed null The relative path of the copy, inside into when given, the same place otherwise.
overwrite bool false true to replace an existing file at the destination.
into ?FilePlace null The place to copy into; the source's place when null.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why.

Returns true once the copy is in place, false when it could not be made. The destination is judged by the destination place's rules as Write judges one, the source is opened once so what is judged is what is copied, and an existing destination is refused unless overwrite is true — as is copying a file onto itself.

// no-check
CkFile::Copy(FilePlace::Uploads, 'in/7f3a.pdf', 'claim-18/scan.pdf', into: FilePlace::Documents);   // true once the copy is in place

Move

A file moved, judged like a write.

static function Move(
    FilePlace $place = FilePlace::Uploads,
    mixed $from = null,
    mixed $to = null,
    bool $overwrite = false,
    ?FilePlace $into = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): bool

The parameters are Copy's. Returns true once the file is in place, false when it could not be moved. The file goes to a temporary name beside its destination first, is judged once more there — in case it changed between the check and the move — and is published into place at the end, so the destination never names a half-moved file; a move that fails puts the file back. An existing destination is refused unless overwrite is true, and so is moving a file onto itself.

// no-check
CkFile::Move(FilePlace::Uploads, 'in/7f3a.pdf', 'claim-18/scan.pdf', into: FilePlace::Documents);   // true once the file is in place

Delete

A file gone.

static function Delete(
    FilePlace $place = FilePlace::Uploads,
    mixed $relative = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): bool

Returns true once no file is at the path — a file that was never there included, so a clean-up needs no Exists first — and false when the path is refused, names a folder, or the file could not be deleted. This deletes files, never folders.

// no-check
CkFile::Delete(FilePlace::Temporary, 'in/7f3a.pdf');   // true once nothing is there

IsAllowed

Whether a place would take a file.

static function IsAllowed(
    FilePlace $place = FilePlace::Uploads,
    mixed $relative = null,
    mixed $bytes = null
): bool
Parameter Type Default What it does
place FilePlace FilePlace::Uploads The place.
relative mixed null The relative path the file would have.
bytes mixed null The file's content; null to judge the name alone.

Returns true when the path passes the gate, its extension is one the place takes and not a blocked one, and — when the bytes are given — they are within the place's limit and their content proves the extension. The check a handler runs before Write, which applies the same rules and says which failed when asked. Never throws.

// no-check
CkFile::IsAllowed(FilePlace::Images, 'avatar.png', $bytes);      // true for a PNG within the limit
CkFile::IsAllowed(FilePlace::Images, 'avatar.php', $bytes);      // false: blocked
CkFile::IsAllowed(FilePlace::Images, 'avatar.png', $pdfBytes);   // false: the content is a PDF
CkFile::IsAllowed(FilePlace::Images, 'avatar.png');              // true: the name alone, judged

AllowedExtensions

The extensions a place takes, in force.

static function AllowedExtensions(FilePlace $place = FilePlace::Uploads): array

Returns the extensions as your application set them, or the library's own list for the place when nothing is set (Your file places, set once): lowercase, without dots, in the order set, never a blocked one. The list an upload form's accept attribute is built from. Never throws.

use SafeCoder\CommonKit\CkFile;
use SafeCoder\CommonKit\Enums\FilePlace;

CkFile::AllowedExtensions(FilePlace::Images);   // -> ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'heic', 'avif']   (as shipped)
CkFile::AllowedExtensions(FilePlace::Archives);   // -> ['zip', '7z', 'rar', 'gz', 'tar']

BlockedExtensions

The extensions no place takes, in force.

static function BlockedExtensions(): array

Returns the library's own (CkSettings::BlockedExtensions) and those your application added in the variable — additions only, the library's own are never taken away. Sorted, lowercase, without dots. Never throws.

use SafeCoder\CommonKit\CkFile;

in_array('php', CkFile::BlockedExtensions(), true);   // -> true
in_array('pdf', CkFile::BlockedExtensions(), true);   // -> false

MaxBytes

The most bytes a file in a place may have, in force.

static function MaxBytes(FilePlace $place = FilePlace::Uploads): int

Returns what your application set for the place, or CkSettings::DefaultMaxFileBytes, 2 MB, when nothing is set. What Write, Copy, Move and Read hold a file to, and the number an upload form shows. Never throws.

use SafeCoder\CommonKit\CkFile;
use SafeCoder\CommonKit\Enums\FilePlace;

CkFile::MaxBytes(FilePlace::Images);   // -> 2097152   (as shipped)

SniffType

The media type a file's bytes prove.

static function SniffType(
    mixed $bytes = null,
    mixed $fallback = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string
Parameter Type Default What it does
bytes mixed null The file's content.
fallback mixed null The type to answer for bytes of no format the library knows; null or empty means no fallback.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkFileException that says why, instead of answering the fallback.

Returns the media type the bytes prove, whatever the file was called: application/pdf for bytes that open with a PDF's signature, image/png for a PNG's, the long Office type for a docx, told from a plain zip by the entries inside; plain text as text/plain, or as text/html, application/json, application/xml or image/svg+xml when it reads as one. The library's own reading of the common document, image, audio, video, archive and font formats, never a guess: bytes of no format it knows answer the fallback. The check behind Write's "the content must prove the extension".

use SafeCoder\CommonKit\CkFile;

CkFile::SniffType("%PDF-1.7\n1 0 obj\n<< /Type /Catalog >>\nendobj\n%%EOF\n");   // -> 'application/pdf'
CkFile::SniffType(hex2bin('89504E470D0A1A0A0000000D49484452'));                  // -> 'image/png'
CkFile::SniffType("id,name\n1,Mary\n");                                           // -> 'text/plain'
CkFile::SniffType('<!DOCTYPE html><html><body>x</body></html>');                   // -> 'text/html'
CkFile::SniffType("\x00\x01\x02", fallback: 'application/octet-stream');          // -> 'application/octet-stream'

IsOfType

Whether bytes are what a type says.

static function IsOfType(
    mixed $bytes = null,
    mixed $type = null
): bool

Returns true when the content is of the type — 'pdf' or 'application/pdf', with or without the extension's dot — judged as SniffType judges it, never by a name. Plain text passes for any text type that has no signature of its own, csv, md, txt, but not for html, which the sniff tells apart; a zip-based format, docx, xlsx, odt, is a zip too. false for no bytes, for a type the library does not know, and for content that proves another type. Never throws.

use SafeCoder\CommonKit\CkFile;

$pdf = "%PDF-1.7\n1 0 obj\n<< /Type /Catalog >>\nendobj\n%%EOF\n";

CkFile::IsOfType($pdf, 'pdf');                // -> true
CkFile::IsOfType($pdf, 'image/png');          // -> false
CkFile::IsOfType("id,name\n1,Mary\n", 'csv');   // -> true   (text is text)

ExtensionFor

The extension for a media type.

static function ExtensionFor(
    mixed $mediaType = null,
    mixed $fallback = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string

Returns the extension for a media type — 'jpg' for image/jpeg, 'pdf' for application/pdf — the reverse of MediaType, from the same fixed table, for naming a file by the type a payload declared. Parameters after a semicolon are dropped and case does not matter; where several extensions share a type the usual one answers. A type the table does not know answers the fallback, '' when there is none; with throwIfInvalid: true the exception says why.

use SafeCoder\CommonKit\CkFile;

CkFile::ExtensionFor('image/jpeg');                                 // -> 'jpg'
CkFile::ExtensionFor('text/html; charset=utf-8');                   // -> 'html'
CkFile::ExtensionFor('application/octet-stream', fallback: 'bin');   // -> 'bin'

UniqueName

A file name that will not collide.

static function UniqueName(
    mixed $input = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string

Returns the value cleaned as FileName cleans it, with a random mark before the extension — scan-3f9a1c7e.pdf, eight hexadecimal characters no two calls share — or '' when nothing usable survives the cleaning. For a stored upload, whose client-side name says what it is but must not be trusted to be unique, and must not be reused as typed. A name too long for the mark is cut to fit, its extension kept. Use it once, when the file is stored, and keep the name.

use SafeCoder\CommonKit\CkFile;

CkFile::UniqueName('scan.pdf');           // 'scan-3f9a1c7e.pdf' — the mark differs every call
CkFile::UniqueName('Report: Q3?.pdf');    // 'Report_ Q3_-7b2d0e41.pdf'

Explain

Why not — in words, without an exception.

static function Explain(
    mixed $input = null,
    ?string $what = 'RelativePath'
): string
Parameter Type Default What it does
input mixed null The raw value.
what ?string 'RelativePath' The reader to judge by: FileName, Extension, RelativePath, FromBase64 or DataUriType, case-insensitive.

Returns

When You get
The value passes the reader ''
It does not The reason, the same words the exception would carry — an answer, not a failure; it never throws

The form-friendly twin of throwIfInvalid: the message to show beside the field, without a try and catch. Every class with a reader has one, on the reader's own rules, so the reason is exactly what the reader would say. This class has several readers, so what names the one to judge by; a name that is no reader answers a note saying so.

use SafeCoder\CommonKit\CkFile;

CkFile::Explain('a/../secrets.txt');   // -> 'it climbs out of its folder (..)'
CkFile::Explain('/etc/passwd');        // -> 'a rooted path'

CkFile::Explain(
    input: 'AAAAA',
    what: 'FromBase64'
);   // -> 'not valid base64'

CkFile::Explain(
    input: 123,
    what: 'FileName'
);   // -> 'a Int32 is not a file name'

The fallback

FileName, Extension and RelativePath take a fallback — a spare value used when the input is rejected. The fallback goes through the exact same processing; a bad fallback answers '' too. FromBase64, DataUriType, HasExtension and the validators take no fallback — the validators' answer is false.

use SafeCoder\CommonKit\CkFile;

CkFile::FileName(
    input: '...',
    fallback: 'upload.bin'
);   // -> 'upload.bin'  (nothing usable survived, so the spare is used)

Good to know

  • Sanitizer vs gate. FileName repairs ('who?.pdf' comes back as 'who_.pdf'); RelativePath rejects (a hostile path "fixed" is still hostile intent). Pick by what the value claims to be: a name, or a path.
  • The readers touch no disk. Every reader works on the text alone — Combine included, which resolves the join itself rather than asking the file system — so a value is judged the same on every machine, and before any folder exists.
  • Every file operation is inside a place. There is no root, no full path in, and no way to reach a folder the application has not named; FullPath is how a path leaves the library for readfile(), a stream or a framework's own storage.
  • The content check is what makes an upload safe, not the name. invoice.pdf.exe fails on its extension, shell.php renamed scan.pdf on its content. An extension the library has no type for — one you listed yourself — cannot be checked and passes on your word; every default list holds only extensions the library can prove.
  • Write, Copy and Move never leave half a file. The bytes go to a dotfile beside the destination, .partial- and sixteen random characters, and are published into place at the end, one step on the same volume. A write that fails leaves nothing behind, and Files never lists the dotfile.
  • Large files are streamed, never read. Read refuses a file over the place's limit, and the limit is small on purpose; a video is served with readfile() or fopen() over FullPath.
  • Delete answers true for a file that was never there. The question it answers is "is it gone", so a clean-up needs no Exists first.
  • UniqueName is random by design. Two calls never agree; use it once, when the file is stored, and keep the name.
  • Serve a place's folder with care. A download through Read or a stream over FullPath sends the type MediaType names. A folder served directly by the web server sends whatever the server maps for each extension, and nothing for one it does not know; keep such a folder to the default lists, whose every extension has a type.
  • Only text is a name, a path or a payload. A string, or an object that writes itself as text, is read; an int, a float, a bool, an array or any other object is refused with "a Int32 is not a file name", "a Boolean is not a path", "a Double is not base64 text" and the like — a name out of an integer column has already lost whatever made it a name. SizeToString is the exception, being a reader of numbers.
  • Reserved names stay defused, even after truncation. Cutting an over-long name can expose a reserved name the first check never saw; FileName checks again after the cut, so CON and friends never slip through.
  • RelativePath rejects three ways out: rooted paths, drive or stream colons, and '..' climbs. Any one of them rejects the whole value.
  • FromBase64 is generous about the text, strict about the verdict. Plain, URL-safe or unpadded base64 and data URIs all decode; whitespace is ignored; input is capped at CkSettings::MaxBase64InputLength characters (about twelve megabytes of file). An empty string always means rejected — and the answer is bytes, never text to clean.
  • DataUriType is shape-checked, not verified. A malformed type answers '', but a well-shaped lie ('image/png' on a ZIP file) passes — check the bytes when it matters.
  • The upload trio. For a data URI upload, run IsDataUri (well-formed, with a payload), InMediaTypes (a type you accept) and IsWithinSize (small enough), then FromBase64 for the bytes. The first three are cheap and never decode.
  • IsSafeFileName rejects where FileName repairs. Same rules, opposite policy: use the validator when a client must send a clean name, the sanitizer when you will clean it yourself.
  • Non-empty in, empty out means rejected. The standard CommonKit signal for the string methods — check for '' where it matters. To pull a file name out of a payload first, see CkDictionary.

Taking an upload

An upload is bytes with a name and a claim about what they are, and all three come from the client. The library's part: clean the name, make it unique, and let the place judge the file — extension, size and content — before a byte is written. The framework hands over the file; the library judges it. In a Laravel controller:

// no-check
use Illuminate\Http\Request;
use SafeCoder\CommonKit\CkFile;
use SafeCoder\CommonKit\CkText;
use SafeCoder\CommonKit\Enums\FilePlace;
use SafeCoder\CommonKit\Exceptions\CkFileException;

Route::post('/claims/{claimId}/documents', function (Request $request, int $claimId) {
    // the bytes: the framework received the file, the library judges it
    $upload = $request->file('scan');
    $bytes = $upload === null ? '' : (string) file_get_contents($upload->getRealPath());

    // the stored name: cleaned, made unique, with the extension the client claimed — the content will have to prove it
    $name = CkFile::UniqueName($upload?->getClientOriginalName());               // 'scan-3f9a1c7e.pdf'
    $path = 'claim-' . CkText::NumberToString($claimId) . '/' . $name;          // 'claim-18/scan-3f9a1c7e.pdf'

    try {
        CkFile::Write(FilePlace::Documents, $path, $bytes, throwIfInvalid: true);
    } catch (CkFileException $refused) {
        // 'a blocked extension (php, a script the web server runs)', 'over 10485760 bytes',
        // 'the content is text/plain, not a pdf file', 'an extension Documents does not take (docx)'
        return response()->json(['error' => $refused->Reason], 400);
    }

    return response()->json(['path' => $path, 'size' => CkFile::SizeToString(strlen($bytes))]);
});

That is the whole gate. The client's name never touches the disk, the file never lands outside the Documents folder, nothing over the limit is kept, and a PDF is a PDF because its bytes say so. Without throwIfInvalid, the same call answers false and IsAllowed is the check to run first when the handler needs no reason. On Joomla! the file comes out of the input object's files, on WordPress out of $_FILES, and the rest is the same three lines; each Frameworks page shows it in place.

A CSV is data as well as a file. Once it is on disk — or instead of storing it — it goes through the pipeline like any other payload:

// no-check
use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkEmail;
use SafeCoder\CommonKit\CkMoney;
use SafeCoder\CommonKit\CkPayload;

if (CkFile::IsOfType($bytes, 'csv')) {
    foreach (CkPayload::FromCsvMaps($bytes) as $row) {
        $email = CkEmail::Address(CkDictionary::String($row, 'email'));
        $amount = CkMoney::Amount(CkDictionary::String($row, 'amount'), 'USD');
        // …
    }
}

The same file inside a JSON body travels as base64, and the pipeline is the usual one: CkPayload gets it off the wire, CkDictionary out of the bag, this class onto the disk:

// no-check
// { "fileName": "scan.pdf", "contentType": "application/pdf", "content": "JVBERi0xLjcK..." }
$bag = CkPayload::FromJson($body);

$bytes = CkFile::FromBase64(CkDictionary::String($bag, 'content'));   // plain base64 or a data URI
$fileName = CkDictionary::String($bag, 'fileName');

if (CkFile::Extension($fileName) === '') {                              // no usable name: name it by its declared type
    $fileName = 'upload.' . CkFile::ExtensionFor(CkDictionary::String($bag, 'contentType'), fallback: 'bin');
}

CkFile::Write(FilePlace::Documents, 'claim-18/' . CkFile::UniqueName($fileName), $bytes, throwIfInvalid: true);

Serving it back is the reverse. A small file is its bytes; a large one is a stream over FullPath, which never loads it:

// no-check
Route::get('/claims/{claimId}/documents/{name}', function (int $claimId, string $name) {
    $path = 'claim-' . CkText::NumberToString($claimId) . '/' . CkFile::FileName($name);

    if (CkFile::Exists(FilePlace::Documents, $path) === false) {
        abort(404);
    }

    return response()->file(CkFile::FullPath(FilePlace::Documents, $path), ['Content-Type' => CkFile::MediaType($path)]);
});

If you want errors instead

Pass throwIfInvalid: true and a value that cannot be used raises a CkFileException (from SafeCoder\CommonKit\Exceptions) instead of answering empty. The exception carries the Input, what was Expected and a short Reason, flattened into a one-line message. Two exceptions to the rule: HasExtension and InMediaTypes take no throwIfInvalid (their allow-list must be the last parameter) — call Extension or DataUriType with it first when you need the error. The validators of the file operations — Exists, IsAllowed, IsOfType — and the lists AllowedExtensions, BlockedExtensions, MaxBytes, Files, ReadOrNull and SizeOrNull never throw either; Write, Copy, Move, Delete, Read, Size, FullPath, SniffType, ExtensionFor and UniqueName take the flag, and their Reason names the rule that refused the file.

use SafeCoder\CommonKit\CkFile;

CkFile::RelativePath(
    input: 'a/../secrets.txt',
    throwIfInvalid: true
);   // throws CkFileException — the message says why