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

2019-01-02 18:49发布

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?

10条回答
看风景的人
2楼-- · 2019-01-02 19:09

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
查看更多
美炸的是我
3楼-- · 2019-01-02 19:11

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;
}
查看更多
君临天下
4楼-- · 2019-01-02 19:13

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

查看更多
只若初见
5楼-- · 2019-01-02 19:15
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?

查看更多
登录 后发表回答