Getting mime type from file name in php

Getting mime type from file name in php

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Why finfo_file Returns application/octet-stream for File Names

Determining the MIME type of a file in PHP is a common requirement when handling uploads or serving static assets. However, there is a critical distinction that often trips up developers: the difference between analyzing the actual file bytes and deriving a type based solely on a filename string.

In your specific case, you are passing $fldrow['field_value'], which contains 'card.pdf'. This value is a string path or name, not a resource handle to an existing file on the filesystem. When you call finfo_file($finfo, $file) with just this string, PHP attempts to interpret it as a file path. If the current working directory does not contain a file literally named card.pdf, the underlying C library returns an error, and finfo_file outputs application/octet-stream.

The Problem with finfo_without_real_files

The function you posted attempts to handle this by falling back to mime_content_type($file). While mime_content_type is useful when analyzing the file extension as a string (which it does support in certain contexts), relying on it requires that the underlying system libraries can parse the extension without checking the file content.

More importantly, both finfo_file and mime_content_type are designed primarily for file content analysis. They inspect the magic bytes at the beginning of a file to determine its true nature. If you pass a string like 'card.pdf' that doesn't correspond to an open file resource or a valid path relative to the current directory, these functions cannot verify the content.

If your application runs in an environment where card.pdf does not exist at the expected path (which is likely if $fldrow['field_value'] is just a raw name from a database), both functions default to application/octet-stream. This indicates "unknown type" rather than inferring it from the .pdf extension.

The Filename Extension Approach

Your edited solution shifts the strategy entirely: you are now parsing the filename string to extract the extension and mapping it to a predefined list of MIME types.

function get_mime_type($filename) {
    $idx = explode('.', $filename);
    $count_explode = count($idx);
    $ext = strtolower($idx[$count_explode-1]);

    $mimet = array( 
        'pdf' => 'application/pdf',
        'png' => 'image/png',
        // ... other mappings
    );

    return isset($mimet[$ext]) ? $mimet[$ext] : 'application/octet-stream';
}

This approach is deterministic. It ignores the filesystem entirely and relies on human-defined conventions. For a file named card.pdf, this will correctly return 'application/pdf'.

Trade-offs and Security Considerations

While your solution solves the immediate problem, relying solely on filename extensions introduces significant security risks. This practice is known as "magic number" bypass vulnerabilities. A malicious actor could rename their payload to card.pdf (triggering your logic) but keep the actual bytes of a shell script or an executable.

If you are serving these files directly to users via HTTP, you must never trust the MIME type derived from a filename alone. Instead, use headers like Content-Disposition: attachment and ensure the file is never served with a browser-renderable content-type unless you have verified the file's integrity.

In modern web frameworks, the preferred workflow involves storing the original filename and extension separately from the stored content hash, then validating the actual file bytes against known magic numbers before serving them. Libraries like finfo work best when passed an actual file path or resource handle:

// Recommended usage with a real file path
$finfo = finfo_open(FILEINFO_MIME_TYPE, FILEINFO_FILEMAGIC | FILEINFO_MIME_EXTENSION);
$mimetype = finfo_file($finfo, '/path/to/actual/file.pdf');
finfo_close($finfo);

If you are using Laravel, consider leveraging the Storage facade to handle file uploads and type detection securely:

https://laravelcompany.com

This resource provides guidance on handling file uploads within the framework, emphasizing secure storage practices over naive extension parsing.

Summary of Decisions

  1. Source Material Analysis: The initial failure was due to passing a string name instead of a real file path to content-analysis functions.
  2. Solution Validity: Your regex/explode-based solution is valid for inferring types from names, but it is not secure for verifying file types.
  3. Implementation Detail: Ensure the extension extraction logic handles edge cases like file.tar.gz correctly if you intend to support complex archives, as a simple explode('.', $filename) will only grab .gz.

For production environments where security is paramount, combine filename-based inference with strict server-side validation of file contents before allowing any action on the file.

Our network