Search by

rikymds / magika-php

RikyMds

Detect the real type of a file from PHP with Google's Magika AI model. Works on shared hosting: no exec(), no native binary, automatic finfo fallback.

Package info

github.com/RikyMds/magika-php

pkg:composer/rikymds/magika-php

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-11-30 11:36 UTC

This package is auto-updated.

Last update: 2026-11-30 11:48:47 UTC


README

tests Packagist License: MIT

Find out what a file really is from PHP, using Magika, Google's open-source deep learning model for file type detection, and check whether its extension tells the truth.

Built to run where PHP usually runs: shared hosting. No exec(), no native binary, no root, and an automatic fallback to finfo if anything goes wrong.

Leer en español

use RikyMds\Magika\FileTypeDetector;
use RikyMds\Magika\Magika;

$detector = new FileTypeDetector(Magika::fromEnv());
$file = $detector->detect($_FILES['doc']['tmp_name'], $_FILES['doc']['name']);

$file->label;             // "png"
$file->mimeType;          // "image/png"
$file->extensionMatches;  // false: it was uploaded as "invoice.pdf"
$file->isAllowed(['pdf']); // false

Why

Checking the extension proves nothing, and finfo (libmagic) only knows formats with a fixed signature. It can't tell CSV from JSON from Python, and some binary formats confuse it too. Magika reads the content with a small neural network and recognises more than 200 content types, text formats included.

Magika is distributed as a Python package and as a native command-line binary. On a typical shared hosting account neither is easy to call from PHP:

  • exec() and shell_exec() are disabled. proc_open() usually is not.
  • The prebuilt magika binary needs a recent glibc (2.38 at the time of writing); many servers run an older one.
  • The system Python is often too old (3.6) for Magika, which needs 3.8+.
  • onnxruntime starts one thread per CPU core and hits the account's process limit: Resource temporarily unavailable.

This package solves each of those: it talks to Magika's Python package through proc_open(), forces a single thread, kills the process after a timeout, and comes with a script that installs a portable Python plus Magika in your home folder, with no root. If Magika is missing, slow or broken, FileTypeDetector quietly falls back to finfo, so your uploads keep working.

Features

  • Framework-agnostic: plain PHP 8.1+, no dependencies. Works with Laravel, Symfony, WordPress or nothing at all.
  • One process per batch: identify a whole multi-file upload in a single run (~0.2–0.3 s including model load).
  • Never breaks your upload flow: timeout, crash, missing Python or magika → finfo fallback, with the reason available in lastError().
  • Honest verdicts: extensionMatches is true, false or null ("can't tell"). A plain text file called .log is not flagged just because it isn't .txt.
  • Upload allow-lists by content: isAllowed(['pdf', 'png']) checks what the file is, not what it's called.
  • magika-check: a diagnostic command that tells you exactly what is missing on your server.
  • install-magika.sh: portable Python + Magika in ~/magika, checksum-verified, no root, no xz needed.

Requirements

  • PHP 8.1 or newer with proc_open() enabled.
  • ext-fileinfo (recommended, for the fallback).
  • Python 3.8+ (CI tests 3.10 to 3.14) with the magika package (about 300 MB with its dependencies). Linux servers need glibc 2.28 or newer for Magika's and onnxruntime's wheels. Without Magika, the package still works, using finfo only.

Installation

composer require rikymds/magika-php

Then install Magika itself. Pick one:

A. You control the server (VPS, Docker, your own machine):

pip install magika
# MAGIKA_PYTHON = output of: which python3

B. Shared hosting (SSH access, no root): run the bundled installer. It downloads a portable Python from python-build-standalone, checks it against the release's SHA256SUMS, and installs Magika into ~/magika:

sh vendor/rikymds/magika-php/scripts/install-magika.sh
# MAGIKA_PYTHON=/home/<you>/magika/python/bin/python3

More detail and troubleshooting: docs/shared-hosting.md.

Check it:

vendor/bin/magika-check --python=/home/<you>/magika/python/bin/python3

Example output on a shared hosting account:

[ OK ] PHP 8.3.6 (Linux)
[ OK ] proc_open() is enabled
[ OK ] Disabled but not needed: exec, shell_exec
[ OK ] ext-fileinfo is loaded (fallback available)
[ OK ] Python found at /home/you/magika/python/bin/python3
[ OK ] Python 3.12.16, libc: glibc 2.28
[ OK ] magika 1.0.3 loaded (model standard_v3_3)
[ OK ] PNG named invoice.pdf -> png (100%), extension mismatch detected
[ OK ] data.csv -> csv (100%)
[ OK ] Two files in 0.27 s (one Python process, model load included)

Magika works on this server.

Usage

Validate an upload

use RikyMds\Magika\FileTypeDetector;
use RikyMds\Magika\Magika;

$detector = new FileTypeDetector(new Magika('/home/you/magika/python/bin/python3'));

$upload = $_FILES['document'];
$file = $detector->detect($upload['tmp_name'], $upload['name']);

if (!$file->isAllowed(['pdf', 'jpg', 'png'])) {
    http_response_code(422);
    exit('Only PDF, JPG or PNG files are accepted.');
}

if ($detector->lastError()) {
    // Magika could not run and finfo decided. Log it: if it happens on every
    // request, the installation is broken.
    error_log('magika-php: ' . $detector->lastError()->getMessage());
}

detect() takes the path of the file to read and, separately, the name the user gave it, because PHP's temporary upload file has no extension.

Several files at once

Starting Python and loading the model is most of the cost, so pass the whole upload in one call:

$files = [];
foreach ($_FILES['files']['tmp_name'] as $i => $tmp) {
    $files[$tmp] = $_FILES['files']['name'][$i];
}

foreach ($detector->detectMany($files) as $path => $file) {
    if ($file->isMismatch()) {
        // e.g. an executable uploaded as holiday.jpg
    }
}

Configuration from the environment

Magika::fromEnv() reads MAGIKA_PYTHON (and optional MAGIKA_TIMEOUT, in seconds, default 10) and returns null when it is not set, which makes FileTypeDetector use finfo only. Handy for local development without Python.

$detector = new FileTypeDetector(Magika::fromEnv());

Laravel validation rule

No Laravel integration is shipped (on purpose: no dependencies), but a rule is a few lines:

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use RikyMds\Magika\FileTypeDetector;
use RikyMds\Magika\Magika;

final class RealFileType implements ValidationRule
{
    /** @param list<string> $allowed */
    public function __construct(private array $allowed) {}

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $file = (new FileTypeDetector(Magika::fromEnv()))
            ->detect($value->getRealPath(), $value->getClientOriginalName());

        if (!$file->isAllowed($this->allowed)) {
            $fail('The :attribute must be a ' . implode(', ', $this->allowed) . ' file.');
        }
    }
}

// $request->validate(['invoice' => ['required', 'file', new RealFileType(['pdf'])]]);

Low level: Magika only

use RikyMds\Magika\Magika;
use RikyMds\Magika\MagikaException;

$magika = new Magika('/usr/bin/python3', timeout: 5);

try {
    $result = $magika->identifyPath('/path/to/file');
    $result->label;                     // "python"
    $result->description;               // "Python source"
    $result->extensions;                // ["py", "pyi"]
    $result->confidence();              // 99
    $result->fileNameMatches('x.txt');  // false
} catch (MagikaException $e) {
    // $e->getCode(): UNAVAILABLE, TIMEOUT or FAILED; $e->stderr() has Python's output
}

What you get back

FileTypeDetector::detect() returns a Detection:

Property / method Type Meaning
detector string "magika" or "finfo": which engine decided
label ?string Magika's label: pdf, png, csv, python… (null with finfo)
description ?string Human-readable type: "PDF document" (null with finfo)
mimeType ?string Real MIME type of the content, null if unknown
declaredExtension string Extension taken from the name you passed ("" if none)
realExtensions list<string> Extensions that fit the content
extensionMatches ?bool Does the declared extension fit? null = can't tell
isMismatch() bool true only when the extension is known to be wrong
isAllowed(array) bool Is the content one of these types? Unknown content is not allowed
confidence ?int Magika's score, 0–100 (null with finfo)
finfoMimeType ?string What finfo says, always computed when ext-fileinfo is loaded
magika ?Result Magika's full answer, when it ran

extensionMatches is null when there is nothing to compare: no extension, content Magika doesn't recognise, or generic text with another extension (a .log or .yml file is plain text too, and that is fine).

How it works

  1. Magika starts python3 resources/magika_helper.py with proc_open() and writes the list of paths to its standard input as JSON.
  2. The helper sets onnxruntime to a single thread, runs Magika on every file and prints one JSON object.
  3. PHP waits up to the timeout (10 s by default), then kills the process if it is still running.
  4. FileTypeDetector turns each answer into a Detection. When Magika is not available or does not recognise a file, it uses finfo and a table of the usual MIME types and extensions.

The files never leave your server: Magika runs locally, and the model ships inside the Python package.

What this is not

It identifies file types. It is not an antivirus: a file whose extension matches can still be malicious, and a mismatch is not proof of malware. Keep the usual upload hygiene: random file names, storage outside the web root, size limits, and never execute or include uploads.

Used in production

ARevo Scanner, a free tool that checks whether a file is really what its extension says, runs the code this package grew out of on shared hosting since September 2026.

Credits and license

Magika is developed by Google and released under the Apache 2.0 license. This package is an independent project and is not affiliated with or endorsed by Google. It does not bundle Magika: it calls the Python package you install.

magika-php is released under the MIT license.