How to get the MIME type of file to download?

I need to download the specified file by clicking on the link for which I used the script below, but when the file is downloaded, it cannot identify the extension of the downloaded file. So, how to get the MIME type of file to upload? _Please, help...

$filename = $_GET['val'];
         // Fetch the file info.
    $filePath = $_SERVER['DOCUMENT_ROOT'] . "dfms/images/uploads/".$filename;


    if(file_exists($filePath)) {
        echo $fileName = basename($filePath);
        $fileSize = filesize($filePath);

        // Output headers.
        header("Cache-Control: private");
        header("Content-Type: application/octet");
        header("Content-Length: ".$fileSize);
        header("Content-Disposition: attachment; filename=".$fileName);

        // Output file.
        readfile ($filePath);                   
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }
+3
source share
1 answer

Using the finfo_file function from the FileInfo extension (enabled by default in PHP 5.3). http://www.php.net/manual/en/function.finfo-file.php

From the example in the documentation

$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo, $filename);
finfo_close($finfo);

In PHP versions prior to 5.3, the pecl extension can install http://pecl.php.net/package/Fileinfo

magic_open (libmagic) http://sourceforge.net/projects/libmagic

mime_content_type($filename) http://au.php.net/manual/en/function.mime-content-type.php

mime.magic

+7

Source: https://habr.com/ru/post/1791415/


All Articles