How to get the content-type of a file in PHP?

試著忘記壹切 提交于 2019-11-26 02:11:56

问题


I\'m using PHP to send an email with an attachment. The attachment could be any of several different file types (pdf, txt, doc, swf, etc).

First, the script gets the file using \"file_get_contents\".

Later, the script echoes in the header:

Content-Type: <?php echo $the_content_type; ?>; name=\"<?php echo $the_file_name; ?>\"

How to I set the correct value for $the_content_type?


回答1:


I am using this function, which includes several fallbacks to compensate for older versions of PHP or simply bad results:

function getFileMimeType($file) {
    if (function_exists('finfo_file')) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $type = finfo_file($finfo, $file);
        finfo_close($finfo);
    } else {
        require_once 'upgradephp/ext/mime.php';
        $type = mime_content_type($file);
    }

    if (!$type || in_array($type, array('application/octet-stream', 'text/plain'))) {
        $secondOpinion = exec('file -b --mime-type ' . escapeshellarg($file), $foo, $returnCode);
        if ($returnCode === 0 && $secondOpinion) {
            $type = $secondOpinion;
        }
    }

    if (!$type || in_array($type, array('application/octet-stream', 'text/plain'))) {
        require_once 'upgradephp/ext/mime.php';
        $exifImageType = exif_imagetype($file);
        if ($exifImageType !== false) {
            $type = image_type_to_mime_type($exifImageType);
        }
    }

    return $type;
}

It tries to use the newer PHP finfo functions. If those aren't available, it uses the mime_content_type alternative and includes the drop-in replacement from the Upgrade.php library to make sure this exists. If those didn't return anything useful, it'll try the OS' file command. AFAIK that's only available on *NIX systems, you may want to change that or get rid of it if you plan to use this on Windows. If nothing worked, it tries exif_imagetype as fallback for images only.

I have come to notice that different servers vary widely in their support for the mime type functions, and that the Upgrade.php mime_content_type replacement is far from perfect. The limited exif_imagetype functions, both the original and the Upgrade.php replacement, are working pretty reliably though. If you're only concerned about images, you may only want to use this last one.




回答2:


It very easy to have it in php.

Simply call the following php function mime_content_type

<?php
    $filelink= 'uploads/some_file.pdf';
    $the_content_type = "";

    // check if the file exist before
    if(is_file($file_link)) {
        $the_content_type = mime_content_type($file_link);
    }
    // You can now use it here.

?>

PHP documentation of the function mime_content_type() Hope it helps someone




回答3:


With finfo_file: http://us2.php.net/manual/en/function.finfo-file.php




回答4:


Here's an example using finfo_open which is available in PHP5 and PECL:

$mimepath='/usr/share/magic'; // may differ depending on your machine
// try /usr/share/file/magic if it doesn't work
$mime = finfo_open(FILEINFO_MIME,$mimepath);
if ($mime===FALSE) {
 throw new Exception('Unable to open finfo');
}
$filetype = finfo_file($mime,$tmpFileName);
finfo_close($mime);
if ($filetype===FALSE) {
 throw new Exception('Unable to recognise filetype');
}

Alternatively, you can use the deprecated mime_ content_ type function:

$filetype=mime_content_type($tmpFileName);

or use the OS's in built functions:

ob_start();
system('/usr/bin/file -i -b ' . realpath($tmpFileName));
$type = ob_get_clean();
$parts = explode(';', $type);
$filetype=trim($parts[0]);



回答5:


function getMimeType( $filename ) {
        $realpath = realpath( $filename );
        if ( $realpath
                && function_exists( 'finfo_file' )
                && function_exists( 'finfo_open' )
                && defined( 'FILEINFO_MIME_TYPE' )
        ) {
                // Use the Fileinfo PECL extension (PHP 5.3+)
                return finfo_file( finfo_open( FILEINFO_MIME_TYPE ), $realpath );
        }
        if ( function_exists( 'mime_content_type' ) ) {
                // Deprecated in PHP 5.3
                return mime_content_type( $realpath );
        }
        return false;
}

This worked for me

Why is mime_content_type() deprecated in PHP?




回答6:


I guess that i found a short way. Get the image size using:

$infFil=getimagesize($the_file_name);

and

Content-Type: <?php echo $infFil["mime"] ?>; name="<?php echo $the_file_name; ?>"

The getimagesize returns an associative array which have a MIME key

I used it and it works




回答7:


I've tried most of the suggestions, but they all fail for me (I'm inbetween any usefull version of PHP apparantly. I ended up with the following function:

function getShellFileMimetype($file) {
    $type = shell_exec('file -i -b '. escapeshellcmd( realpath($_SERVER['DOCUMENT_ROOT'].$file)) );
    if( strpos($type, ";")!==false ){
        $type = current(explode(";", $type));
    }
    return $type;
}



回答8:


There is the function header:

 header('Content-Type: '.$the_content_type);

Note that this function has to be called before any output. You can find further details in the reference http://php.net/header

Edit:

Ops, I've misunderstood the question: Since php 4.0 there is the function mime_content_type to detect the mimetype of a file.

In php 5 is deprecated, should be replaced by the file info set of functions.




回答9:


I really recommend using a Framework like "CodeIgniter" for seinding Emails. Here is a Screencast about "Sending Emails with CodeIgniter" in only 18 Minutes.

http://net.tutsplus.com/videos/screencasts/codeigniter-from-scratch-day-3/




回答10:


try this:

function ftype($f) {
                    curl_setopt_array(($c = @curl_init((!preg_match("/[a-z]+:\/{2}(?:www\.)?/i",$f) ? sprintf("%s://%s/%s", "http" , $_SERVER['HTTP_HOST'],$f) :  $f))), array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_HEADER => 1));
                        return(preg_match("/Type:\s*(?<mime_type>[^\n]+)/i", @curl_exec($c), $m) && curl_getinfo($c, CURLINFO_HTTP_CODE) != 404)  ? ($m["mime_type"]) : 0;

         }
echo ftype("http://img2.orkut.com/images/medium/1283204135/604747203/ln.jpg"); // print image/jpeg


来源:https://stackoverflow.com/questions/1232769/how-to-get-the-content-type-of-a-file-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!