문제

I'm uploading images from my Android app to my server. The app uses the android camera intent and upload via PHP script is ok.

I want to verify if the uploaded files are real images, I'm not checking the extension but the mimetype (I suppose this is the best way to do it, tell me if I'm wrong).

I'm using a Slackware Linux Apache server and I'm trying this code:

....
$finfo = finfo_open(FILEINFO_MIME, '/etc/httpd/magic');
....
fwrite($fp, finfo_file($finfo, "file.jpg"));
....

But I'm getting "application/octet-stream; charset=binary" instead of "image/jpeg; charset=binary" which is given from "file -i file.jpg" (shell command).

What's the problem?

도움이 되었습니까?

해결책

Solved using $finfo = finfo_open(FILEINFO_MIME); instead of the other line. I think the default magic file is not the same that I was specifing.

다른 팁

As refered on www.php.net/manual/en/ref.fileinfo.php:

<?php

function is_jpg($fullpathtoimage){
    if(file_exists($fullpathtoimage)){
        exec("/usr/bin/identify -format %m $fullpathtoimage",$out);
        //using system() echos STDOUT automatically
        if(!empty($out)){
            //identify returns an empty result to php
            //if the file is not an image

            if($out == 'JPEG'){
                return true;
            }
        }
    }
    return false;
}

?>

Alternately, if you've got execution rights and want to use a "hacky" solution, you can simply do what you've already done (using file -i path with shell_exec):

<?php
    function shell_get_mime_type($path) {
        if (is_readable($path)) {
            $command = 'file -i "' . realpath($path) . '"';

            $shellOutput = trim(shell_exec($command));
            //eg. "nav_item.png: image/png; charset=binary"

            if (!empty($shellOutput)) {
                $colonPosition = strpos($shellOutput, ':');

                if ($colonPosition !== false) {
                    return rtrim(substr($shellOutput, $colonPosition + 1));
                }

                return $shellOutput;
            }
        }

        return false;
    }
?>

Try to use function mime_content_type().

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top