sanitize_filename()
function sanitize_filename(string $filename, bool $transliteration = true, int $max_length = 200): string
Description
Sanitizes a filename for safe storage and usage. This function transliterates international characters, removes or replaces special characters and whitespace, preserves file extensions, prevents null byte attacks, generates fallback names for edge cases, and limits filename length to prevent filesystem issues.
Parameters
| Parameter | Type | Description | Default |
|---|---|---|---|
| $filename | string | The filename to sanitize. | N/A |
| $transliteration | bool | Whether to transliterate international characters to ASCII. | true |
| $max_length | int | Maximum length for the base filename, excluding extension. | 200 |
Return Value
| Type | Description |
|---|---|
| string | The sanitized filename with preserved extension. |
Example Usage
PHP
echo sanitize_filename('My Photo (1).jpg');
// "my-photo-1.jpg"
echo sanitize_filename('Москва 2024.png');
// "moskva-2024.png" (with intl)
echo sanitize_filename('file@#$%.txt');
// "file.txt"
echo sanitize_filename('my multiple spaces.txt');
// "my-multiple-spaces.txt"