PHP for detecting the MIME type of an uploaded file using magic bytes


PHP Code to Detect MIME Type of Uploaded File Using Magic Bytes

<?php

// Define the function to detect the MIME type of an uploaded file
function detectMimeType($file) {
  // Convert the uploaded file to a string
  $fileContent = file_get_contents($file['tmp_name']);

  // Get the first few bytes of the file
  $magicBytes = substr($fileContent, 0, 4);

  // Map the magic bytes to the corresponding MIME type
  $mimeTypes = array(
    'FFD8' => 'image/jpeg',
    '8950' => 'image/png',
    '4749' => 'image/gif',
    '4D4D' => 'image/tiff',
    '2550' => 'application/pdf',
    '504B' => 'application/zip',
    '425A' => 'application/bzip2',
    '7573' => 'text/plain',
    '3C3F' => 'text/html',
    '4D5A' => 'application/x-lzip',
    '6D6F' => 'application/x-lzma',
    '5261' => 'application/x-rar-compressed',
    '4357' => 'application/x-7z-compressed',
    '7801' => 'application/x-xz'
  );

  // Get the MIME type from the magic bytes
  $mimeType = array_key_exists($magicBytes, $mimeTypes) ? $mimeTypes[$magicBytes] : 'unknown';

  // Return the MIME type
  return $mimeType;
}

// Example usage
$file = $_FILES['file'];
$mimeType = detectMimeType($file);

// Print the MIME type
echo "The MIME type of the uploaded file is: " . $mimeType;

How it Works

The code works by reading the first few bytes of the uploaded file, known as the "magic bytes." These magic bytes are specific to different file types and serve as a signature for identifying the file’s format.

The code uses a mapping of these magic bytes to their corresponding MIME types. By comparing the magic bytes of the uploaded file to the entries in this mapping, the code can determine the MIME type of the file.

How to Implement

To implement this solution effectively, follow these steps:

  1. Create a function called detectMimeType that takes the uploaded file as an argument.
  2. Convert the uploaded file to a string using file_get_contents.
  3. Get the first few bytes of the file using substr.
  4. Map the magic bytes to their MIME types using an array.
  5. Compare the magic bytes of the uploaded file to the entries in the mapping to determine the MIME type.
  6. Return the MIME type.
  7. Call the detectMimeType function to detect the MIME type of the uploaded file.

This solution provides a reliable way to detect the MIME type of an uploaded file, allowing you to handle different file formats appropriately in your PHP applications.