PHPackages                             andreinocenti/file-type-detector-php - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. andreinocenti/file-type-detector-php

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

andreinocenti/file-type-detector-php
====================================

A PHP Lib to detect file type (category, MIME, extension) from local paths, URLs or data URIs using MIME, extensions, magic numbers and HTTP HEAD.

v1.0.0(7mo ago)073↓50%MITPHPPHP &gt;=8.2

Since Oct 1Pushed 7mo agoCompare

[ Source](https://github.com/andreinocenti/file-type-detector-php)[ Packagist](https://packagist.org/packages/andreinocenti/file-type-detector-php)[ RSS](/packages/andreinocenti-file-type-detector-php/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (1)Versions (2)Used By (0)

File Type Detector (PHP) — detect file type via MIME, extension, magic numbers, and HTTP HEAD
=============================================================================================

[](#file-type-detector-php--detect-file-type-via-mime-extension-magic-numbers-and-http-head)

A **PHP package** to accurately identify a file type from a **local path**, **URL (HEAD)**, or **Data URI**, combining multiple strategies: `finfo` (real MIME), **binary signatures (magic numbers)**, **extension lookups**, and **HTTP HEAD Content-Type** (with **SSRF/security** controls). Perfect for **upload validation**, **download gatekeeping**, **conditional processing** (e.g., images vs. docs), and **indexing**.

> PHP MIME detection, detect file type by extension and magic number, validate uploads in Laravel/PHP, detect docx/xlsx/pptx, detect mp4/m4a/heic/avif, tell zip vs docx, anti-SSRF HTTP HEAD.

---

✨ Highlights
------------

[](#-highlights)

- **Multi-strategy**: `finfo` → **smart refinements** → **magic** → **extension** (fallback).
- **Family-level refinements**:
    - **ZIP**: distinguishes plain `.zip` from `docx/xlsx/pptx`, **EPUB**, **ODF** (odt/ods/odp), **JAR**, **APK**, **3MF**, **KMZ** by peeking internal entries.
    - **EBML**: distinguishes **WebM** vs **Matroska (MKV)**.
    - **ISO-BMFF**: identifies **MP4/M4A/HEIC/AVIF** based on **ftyp brand**.
- **Security** (URLs): protections against **SSRF**, **unsafe redirects**, **limited protocols**, **timeouts**, **allow-/block-lists**, **private network blocking** (optional).
- **Configurable overrides**: inject your own **ext→mime** and **mime→category** maps without touching the core.
- **Simple, typed API** (PHP 8.2+), PSR-12 compliant.

---

🧩 Supported types &amp; extensions
----------------------------------

[](#-supported-types--extensions)

Below is a snapshot (non-exhaustive; you can expand via overrides).

### Images

[](#images)

ExtensionsPrimary MIMECategoryjpg, jpegimage/jpegimagepngimage/pngimagegifimage/gifimagewebpimage/webpimageavifimage/avifimageheic, heifimage/heic, image/heifimagetiff, tifimage/tiffimagebmpimage/bmpimageicoimage/vnd.microsoft.iconimagepsdimage/vnd.adobe.photoshopimagesvgimage/svg+xmlimagecr2, nef, arw, dngimage/x-\* (raw)raw-image### Video

[](#video)

ExtensionsPrimary MIMECategorymp4, m4vvideo/mp4videowebmvideo/webmvideomkvvideo/x-matroskavideomovvideo/quicktimevideo3gpvideo/3gppvideo### Audio

[](#audio)

ExtensionsPrimary MIMECategorymp3audio/mpegaudiowavaudio/wavaudioflacaudio/flacaudioogg, ogaaudio/oggaudioopusaudio/opusaudioaacaudio/aacaudiom4aaudio/mp4audiomid, midiaudio/midiaudiocafaudio/x-cafaudio### Documents / Text / Code

[](#documents--text--code)

ExtensionsPrimary MIMECategorypdfapplication/pdfpdfdocapplication/msworddocumentdocxapplication/vnd.openxmlformats-officedocument.wordprocessingml.documentdocumentxlsapplication/vnd.ms-excelspreadsheetxlsxapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheetspreadsheetpptapplication/vnd.ms-powerpointpresentationpptxapplication/vnd.openxmlformats-officedocument.presentationml.presentationpresentationrtfapplication/rtfdocumentodt, ods, odpapplication/vnd.oasis.opendocument.\*document/spreadsheet/presentationepubapplication/epub+zipebooktxttext/plaintextcsvtext/csvspreadsheetmdtext/markdowntexthtml, htmtext/htmlcodejsonapplication/jsoncodexmlapplication/xmlcodeyaml, ymltext/yamlcodephp, js, csstext/x-php, application/javascript, text/csscode### Compressed / Packaged

[](#compressed--packaged)

ExtensionsPrimary MIMECategoryzip, cbzapplication/ziparchive7zapplication/x-7z-compressedarchiverar, cbrapplication/x-rar-compressedarchivetarapplication/x-tararchivegzapplication/x-gziparchivebz2application/x-bzip2archivexzapplication/x-xzarchivezstapplication/zstdarchivejarapplication/java-archivecodeapkapplication/vnd.android.package-archivecodekmzapplication/vnd.google-earth.kmzgis3mfmodel/3mf3d-model### Executables / Fonts / Others

[](#executables--fonts--others)

ExtensionsPrimary MIMECategoryexeapplication/x-dosexecexecutableelfapplication/x-executableexecutablemach-oapplication/x-mach-binaryexecutablettf, otf, woff, woff2font/\*fontisoapplication/x-iso9660-imagedisk-imagetorrentapplication/x-bittorrenttorrentm3u, m3u8, plsaudio/x-mpegurl, application/vnd.apple.mpegurl, application/pls+xmlplaylistsrt, vtt, ass, ssaapplication/x-subrip, text/vtt, text/x-ssasubtitlepem, der, p7m, p7sx509/pkcs7certificateicstext/calendarcalendarvcftext/vcardcontactemlmessage/rfc822emailkmlapplication/vnd.google-earth.kml+xmlgisgpxapplication/gpx+xmlgisobj, stl, gltfmodel/\*3d-modelstep, stp, iges, igs, dxf, dwgmodel/\* or image/vnd.\*cad> You can **extend/modify** via **overrides**; see below.

---

📦 Installation
--------------

[](#-installation)

```
composer require andreinocenti/file-type-detector-php
```

Requirements:

- **PHP 8.2+**
- **fileinfo** extension enabled (for `finfo`)
- (Optional) **cURL** for more robust HEAD on URLs

---

🚀 Basic Usage
-------------

[](#-basic-usage)

```
use AndreInocenti\FileTypeDetector\FileTypeDetector;

$detector = new FileTypeDetector();

// 1) Local path
$result = $detector->detect('/path/to/file.png');
/*
$result->toArray():
[
  'category'   => 'image',
  'mime'       => 'image/png',
  'extension'  => 'png',
  'confidence' => 0.95,
  'source'     => 'mime' // mime | magic | extension | http-head | data-uri
]
*/

// 2) URL (HEAD only, safe)
$result = $detector->detect('https://cdn.example.com/file');
// Uses Content-Type and, when needed, "Content-Disposition: filename=..." and/or URL path extension.

// 3) Data URI
$result = $detector->detect('data:image/png;base64,iVBORw0KGgo=');
```

### Detection order

[](#detection-order)

1. **finfo (MIME)** → **Family refinements**:
    - **ZIP** (docx/xlsx/pptx/epub/odf/jar/apk/3mf/kmz),
    - **EBML** (webm/mkv),
    - **ISO-BMFF** (mp4/m4a/heic/avif). If MIME is **weak** (`application/octet-stream`, `text/plain`, `inode/x-empty`, etc.), we **prefer extension** if reliable.
2. **Magic numbers** → same refinements.
3. **Extension** (fallback).
4. **URL**: **HEAD** (Content-Type) + **Content-Disposition** filename + path extension.

---

🧩 Enums
-------

[](#-enums)

- `FileCategory`: IMAGE, VIDEO, AUDIO, DOCUMENT, SPREADSHEET, PRESENTATION, PDF, ARCHIVE, EXECUTABLE, FONT, DISK\_IMAGE, TORRENT, CODE, TEXT, EBOOK, CONTACT, CALENDAR, SUBTITLE, CERTIFICATE, GIS, 3D\_MODEL, CAD, RAW\_IMAGE, UNKNOWN.

Eg:

```
use AndreInocenti\FileTypeDetector\Enums\FileCategory;
if ($result->category === FileCategory::IMAGE->value) {
    // process image
}
```

---

🔧 Overrides (external config)
-----------------------------

[](#-overrides-external-config)

Inject your own mappings without touching the core:

```
use AndreInocenti\FileTypeDetector\FileTypeDetector;
use AndreInocenti\FileTypeDetector\Enums\FileCategory;

$extOverrides = [
    'abc' => 'application/x-custom', // map ".abc" to x-custom
];

$mimeCatOverrides = [
    'application/x-custom' => FileCategory::DOCUMENT, // category for your custom MIME
];

$detector = new FileTypeDetector(
    http: null,                         // default HTTP client
    extToMimeOverrides: $extOverrides,  // your mappings
    mimeToCategoryOverrides: $mimeCatOverrides
);

$res = $detector->detect('/files/report.abc');
```

### Override tips

[](#override-tips)

- Use overrides for **proprietary** types, internal extensions, or to **normalize categories** in your domain.
- Overrides **take precedence** over package defaults.

---

🛡️ Security hardening (URLs)
----------------------------

[](#️-security-hardening-urls)

The package ships with `NativeHttpClient` + `SecurityOptions`:

```
use AndreInocenti\FileTypeDetector\FileTypeDetector;
use AndreInocenti\FileTypeDetector\Config\SecurityOptions;
use AndreInocenti\FileTypeDetector\Http\NativeHttpClient;

$security = new SecurityOptions(
    allowPrivateNetworks: false,          // blocks 10.0.0.0/8, 192.168.0.0/16, 127.0.0.1, ::1, etc.
    allowedSchemes: ['https'],            // HTTPS only
    allowedHosts: ['cdn.yoursite.com'],     // optional allow-list
    blockedHosts: ['example-insecure.com'], // optional block-list
    timeout: 8,                           // seconds
    maxRedirects: 3,                      // manual redirects
    userAgent: 'Yoursite-FileTypeDetector/1.0'
);

$http = new NativeHttpClient($security);
$detector = new FileTypeDetector($http, [], [], $security);

$res = $detector->detect('https://cdn.yoursite.com/file');
```

**Protected by default:**

- **SSRF**: resolves DNS → validates **public IPs only** (when `allowPrivateNetworks=false`).
- **Redirects**: handled **manually** and re-validated at every hop (scheme/host/IP).
- **Protocols**: `http/https` only by default.
- **Timeouts** and **User-Agent** configurable.
- **Allow-/block-lists** by host (optional).

> If you **must** reach internal hosts (intranet), set `allowPrivateNetworks=true` **only** in trusted environments.

---

🧪 Tests
-------

[](#-tests)

Uses **Pest** + PHPUnit CodeCoverage.

```
composer install
vendor/bin/pest
# Coverage
XDEBUG_MODE=coverage vendor/bin/pest --coverage
```

---

📚 API (quick reference)
-----------------------

[](#-api-quick-reference)

```
FileTypeDetector::__construct(
    ?HttpClientInterface $http = null,
    array $extToMimeOverrides = [],
    array $mimeToCategoryOverrides = [],
    ?SecurityOptions $security = null
)

```

- **$http**: HTTP client for HEAD; defaults to `NativeHttpClient` with `SecurityOptions`.
- **$extToMimeOverrides**: override extension→MIME.
- **$mimeToCategoryOverrides**: override MIME→Category.
- **$security**: HTTP security policy.

### `FileTypeDetector::detect(string $input): FileTypeResult`

[](#filetypedetectordetectstring-input-filetyperesult)

- **$input**: local path, **URL** (http/https), or **data:** URI.
- **Returns**: `category`, `mime`, `extension`, `confidence`, `source`.

---

Confidence Level
----------------

[](#confidence-level)

- `ConfidenceLevel`: HIGH (0.95), MEDIUM (0.75), LOW (0.5), VERY\_LOW (0.25), NONE (0.0).

📄 License
---------

[](#-license)

**MIT** — free for commercial and open-source projects.

---

🙋 Support &amp; Contributions
-----------------------------

[](#-support--contributions)

- Issues and PRs are welcome.
- Share real-world “tricky files” to help expand coverage and heuristics.

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance64

Regular maintenance activity

Popularity11

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Unknown

Total

1

Last Release

221d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/9d5b3ad27cc2ab495bd40b9837f085b35efd442cbd88ceac5971f273ecdd88a6?d=identicon)[andreinocenti](/maintainers/andreinocenti)

---

Top Contributors

[![andreinocenti](https://avatars.githubusercontent.com/u/39701679?v=4)](https://github.com/andreinocenti "andreinocenti (25 commits)")

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/andreinocenti-file-type-detector-php/health.svg)

```
[![Health](https://phpackages.com/badges/andreinocenti-file-type-detector-php/health.svg)](https://phpackages.com/packages/andreinocenti-file-type-detector-php)
```

###  Alternatives

[cubear/finder

Finder is a Drupal 8 module to help users find services which meet their criteria

404.2k](/packages/cubear-finder)

PHPackages © 2026

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