简体   繁体   中英

How to get the mime content type from 'php://input' in PHP

The images are dropped on an area, and then, have to be automatically saved on server.

Images are send throw an AJAX request.

I would like to check the mime type from the server side to be sure I will not save anything unsafe.

The headers are not really a solution, because they come from the client side, so they can be changed.

PHP

I receive the file like this :

$source = file_get_contents('php://input');

I tried to get the mime type with

mime_content_type($filename);

and

finfo_file($finfo, $filename);

but what is $filename in my case ? It doesn't work with

$filename = 'php://input';

Can I get the mime content type from a different way ?

AJAX

addEvent(canvas, 'drop', function(e) {
    e.preventDefault();
    var files = e.dataTransfer.files;
    upload(files,e.target,0);
});

function upload(files, area, index){
    var file = files[index];
    xhr.open("post", "/index.php", true);
    xhr.setRequestHeader("content-type", "multipart/form-data");
    xhr.setRequestHeader("X-File-Type", file.type);
    xhr.setRequestHeader("X-File-Size", file.size);

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
            read(xhr.responseText);
        }
    }

    xhr.send(file);
}

Any idea ?

Thank you Cyclone, I did this:

To save in a temporary file :

$temp_file = tempnam(sys_get_temp_dir(), 'Tux');  
file_put_contents($temp_file , $source); 

To get the mime content type :

$finfo = finfo_open(FILEINFO_MIME_TYPE);  
$content_type = finfo_file($finfo, $temp_file);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM