Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

finfo

finfo is a native PHP class, part of the Fileinfo extension, that detects the MIME type and encoding of a file or a string buffer by inspecting its content, using the libmagic library, rather than trusting its filename or extension.

finfo is instantiated with a mode constant, such as FILEINFO_MIME_TYPE, and then queried with $finfo->file($path) or $finfo->buffer($content).

Since the value provided by $_FILES[...]['type'] is supplied by the client and cannot be trusted, finfo is the recommended way to validate the real type of an uploaded file before storing or processing it. It replaces the deprecated mime_content_type() function.

<?php

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mimeType = $finfo->file($_FILES['userfile']['tmp_name']);

    if ($mimeType !== 'image/png') {
        throw new RuntimeException('Only PNG files are allowed.');
    }

?>

Documentation

See Also