PHP code example of nguyenquocanhz / mime-type

1. Go to this page and download the library: Download nguyenquocanhz/mime-type library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nguyenquocanhz / mime-type example snippets




use Gems\Mime\MimeType;
use Gems\Mime\MimeMap;

$mime = new MimeType();
$mime->fromPath('/var/www/app.css');   // text/css
$mime->detect('/tmp/upload');          // đọc magic bytes, bỏ qua đuôi file
$mime->fromBuffer($blob);              // cho dữ liệu trong RAM

$mime = new MimeType(baseDir: __DIR__ . '/uploads');   // khóa trong thư mục này

$mime->sendHeaders($path);
readfile($path);

use Gems\Mime\MimeException;

try {
    $name = $mime->validateUpload($_FILES['avatar'], MimeMap::SAFE_IMAGES, maxBytes: 2 * 1024 * 1024);
    move_uploaded_file($_FILES['avatar']['tmp_name'], __DIR__ . "/uploads/$name");
} catch (MimeException $e) {
    error_log($e->getMessage());   // chỉ log, đừng echo — chứa đường dẫn server
    http_response_code(422);
    exit('File không hợp lệ');
}

// ❌ LFI
$mime = new MimeType();
$mime->sendHeaders($_GET['file']);

// ✅
$mime = new MimeType(baseDir: __DIR__ . '/public/files');
$mime->sendHeaders(__DIR__ . '/public/files/' . basename($_GET['file']));