PHPackages                             ondrej-vrto/php-filename-sanitize - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. ondrej-vrto/php-filename-sanitize

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

ondrej-vrto/php-filename-sanitize
=================================

Removes all forbidden characters from the file name or path.

1.6.0(2y ago)1120.6k↓29.8%[1 PRs](https://github.com/OndrejVrto/php-filename-sanitize/pulls)1MITPHPPHP &gt;=4.0.7CI passing

Since Dec 3Pushed 1y ago1 watchersCompare

[ Source](https://github.com/OndrejVrto/php-filename-sanitize)[ Packagist](https://packagist.org/packages/ondrej-vrto/php-filename-sanitize)[ Docs](https://github.com/OndrejVrto/php-filename-sanitize)[ GitHub Sponsors](https://github.com/OndrejVrto)[ RSS](/packages/ondrej-vrto-php-filename-sanitize/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (8)Dependencies (4)Versions (14)Used By (1)

[![Social Card of PHP Filename Sanitize](./Art/socialcard.png)](./Art/socialcard.png)

Removes all forbidden characters from the file name
===================================================

[](#removes-all-forbidden-characters-from-the-file-name)

[![Latest Version on Packagist](https://camo.githubusercontent.com/12c65cb93b339413ac62381968b141cc79f0de367b935226601c4f5e890e6f89/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f6e6472656a2d7672746f2f7068702d66696c656e616d652d73616e6974697a652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ondrej-vrto/php-filename-sanitize)[![Tests](https://camo.githubusercontent.com/b8b9817a6bd50a37d13bb408100fa9db95e16056c356bb131d7ade357090f27a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f4f6e6472656a5672746f2f7068702d66696c656e616d652d73616e6974697a652f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/OndrejVrto/php-filename-sanitize/blob/main/.github/workflows/run-tests.yml)[![Total Downloads](https://camo.githubusercontent.com/f5aac2ec3884791b59107b198c61ff3e85aba2bb4557070539c758be4fe35e0f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f6e6472656a2d7672746f2f7068702d66696c656e616d652d73616e6974697a652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ondrej-vrto/php-filename-sanitize)

Do you store files from the user on the server? Will the uploaded file be accessible in the application via a URL address? Don't want to lose the original file name?

Want to avoid meaningless randomly generated names? This package will help you solve your problem.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require ondrej-vrto/php-filename-sanitize
```

Basic usage
-----------

[](#basic-usage)

```
use OndrejVrto\FilenameSanitize\FilenameSanitize;

$filename = '[file#name].jpg';

$sanitize_filename = FilenameSanitize::of($filename)->get();
// Output: file-name.jpg
```

What problems does the package try to eliminate?
------------------------------------------------

[](#what-problems-does-the-package-try-to-eliminate)

1. Replace special characters
    - [file system reserved](https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words)
    - [control characters](http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx)
    - non-printing characters DEL, NO-BREAK SPACE, SOFT HYPHEN
    - [URI reserved](https://www.rfc-editor.org/rfc/rfc3986#section-2.2)
    - [URL unsafe characters](https://www.ietf.org/rfc/rfc1738.txt)
2. Reduce some consecutive characters (spaces, undescores, dashes, dots)
3. [Windows reserved names](https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file)
4. [Lowercase for windows/unix interoperability](https://en.wikipedia.org/wiki/Filename)
5. [Max filename length to 255 bytes](http://serverfault.com/a/9548/44086)

### Examples

[](#examples)

Strings are sanitized and soft slugged (in addition to dashes, dots are also used).

```
file-name.ext                            ->  file-name.ext
火|车..票                                 ->  火-车.票
.github                                  ->  .github
filename                                 ->  filename
.env.test                                ->  .env.test
File NaME.Zip                            ->  file-name.zip
file___name.zip                          ->  file-name.zip
file---name.zip                          ->  file-name.zip
file...name..zip                         ->  file.name.zip
filename":.zip:                       ->  file-name.zip
~file-{name}^.[zip]                      ->  file-name.zip
   file  name  .   zip                   ->  file-name.zip
[file~name].{jpg}                        ->  file-name.jpg
file--.--.-.--name.zip                   ->  file.name.zip
file-name|#[]&@()+,;=.zip                ->  file-name.zip
alert(1);               ->  script
`rm -rf `  ->  php-malicious-function-rm-rf
```

Advanced settings
-----------------

[](#advanced-settings)

### Create instance

[](#create-instance)

```
// classic object
(new FilenameSanitize($filename))->get();
// or static instance
FilenameSanitize::of($filename)->get();
```

### Directory features

[](#directory-features)

```
FilenameSanitize::of('/some#/di[]r/file#name.jpg')
    ->withSubdirectory()
    ->get();
// Output: \some\dir\file-name.jpg

FilenameSanitize::of('/some#/di[]r/file#name.jpg')
    ->addSubdirectoryToFilename()
    ->get();
// Output: some-dir-file-name.jpg

FilenameSanitize::of('/some#/di[]r/file#name.jpg')
    ->withBaseDirectory("/base/directory")
    ->get();
// Output: \base\directory\file-name.jpg

// together
FilenameSanitize::of('/some#/di[]r/file#name.jpg')
    ->withBaseDirectory("/base/directory")
    ->addSubdirectoryToFilename()
    ->withSubdirectory()
    ->get();
// Output: \base\directory\some\dir\some-dir-file-name.jpg
```

### Extension features

[](#extension-features)

```
FilenameSanitize::of('file_name.jpg')
    ->withNewExtension('webp')
    ->get();
// Output: file-name.webp

FilenameSanitize::of('file_name.jpg')
    ->addActualExtensionToFilename()
    ->get();
// Output: file-name-jpg.jpg

// together
FilenameSanitize::of('file_name.jpg')
    ->addActualExtensionToFilename()
    ->withNewExtension('webp')
    ->get();
// Output: file-name-jpg.webp
```

### Prefix, suffix features

[](#prefix-suffix-features)

```
FilenameSanitize::of('file_name.jpg')
    ->widthFilenameSuffix('suffix')
    ->widthFilenamePrefix('prefix')
    ->get();
// Output: prefix-file-name-suffix.jpg
```

### Default name if sanitized filename is empty

[](#default-name-if-sanitized-filename-is-empty)

```
FilenameSanitize::of(null)
    ->get();
// throw ValueError exception

FilenameSanitize::of(null)
    ->defaultFilename('default-file-name.jpg')
    ->get();
// Output: default-file-name.jpg
```

### Disable conversion to lowercase letters

[](#disable-conversion-to-lowercase-letters)

```
FilenameSanitize::of('File*NAME.Ext')
    ->disableLowerCase()
    ->get();
// Output: File-NAME.Ext
```

### Custom separator

[](#custom-separator)

```
FilenameSanitize::of('file#name.jpg')
    ->customSeparator('_-_')
    ->get();
// Output: file_-_name.jpg
```

Warning: Changing the separator can sometimes lead to unwanted side effects. Individual separator characters are removed from the beginning and end of the file name and extension.

```
FilenameSanitize::of('file#name.ext')
    ->customSeparator('ef')
    ->get();
// Output: ileefnam.xt
```

### A combination of all functions together

[](#a-combination-of-all-functions-together)

```
FilenameSanitize::of('foo2\bar2\file-name.jpg')
    ->addActualExtensionToFilename()
    ->withBaseDirectory('C:/foo/bar')
    ->widthFilenameSuffix('surfix')
    ->widthFilenamePrefix('prefix')
    ->addSubdirectoryToFilename()
    ->withNewExtension('webp')
    ->customSeparator('_')
    ->withSubdirectory()
    ->get();
// Output:  C:\foo\bar\foo2\bar2\prefix_foo2_bar2_file_name_surfix_jpg.webp
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Credits
-------

[](#credits)

- [Ondrej Vrťo](https://github.com/OndrejVrto)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance31

Infrequent updates — may be unmaintained

Popularity34

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 70.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~19 days

Recently: every ~33 days

Total

8

Last Release

762d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ef50ff0349871cc35df4a7d2a2d322972942cab3f1756eb79938694b6eced489?d=identicon)[OndrejVrto](/maintainers/OndrejVrto)

---

Top Contributors

[![OndrejVrto](https://avatars.githubusercontent.com/u/32365016?v=4)](https://github.com/OndrejVrto "OndrejVrto (52 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (13 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (8 commits)")[![williamdes](https://avatars.githubusercontent.com/u/7784660?v=4)](https://github.com/williamdes "williamdes (1 commits)")

---

Tags

phpcleansanitizefilenameondrej vrto

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/ondrej-vrto-php-filename-sanitize/health.svg)

```
[![Health](https://phpackages.com/badges/ondrej-vrto-php-filename-sanitize/health.svg)](https://phpackages.com/packages/ondrej-vrto-php-filename-sanitize)
```

###  Alternatives

[surgiie/transformer

A data transforming/formatting package for php.

12724.3k1](/packages/surgiie-transformer)[mathiasreker/php-svg-optimizer

php-svg-optimizer is a PHP library designed to optimize SVG files by applying various transformations and cleanup operations.

338.9k2](/packages/mathiasreker-php-svg-optimizer)[erlandmuchasaj/sanitize

A package to sanitize your input.

146.0k](/packages/erlandmuchasaj-sanitize)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
