How to determine the file type of binary stream in php

WBOY
Release: 2016-10-10 11:55:53
Original
2973 people have browsed it

I recently used the following method to judge: download the file, get the file stream->store to the hard disk->determine the file type.
But I think this seems redundant. Can I determine the file type without saving after file_get_contents()?

<code class="php">$image=file_get_contents($url);
file_put_contents($imagePath, $image);   //将图片流存入服务器图片目录
$type=image_type_to_extension(exif_imagetype($imagePath));   //文件类型</code>
Copy after login
Copy after login

Reply content:

I recently used the following method to judge: download the file, get the file stream->store to the hard disk->determine the file type.
But I think this seems redundant. Can I determine the file type without saving after file_get_contents()?

<code class="php">$image=file_get_contents($url);
file_put_contents($imagePath, $image);   //将图片流存入服务器图片目录
$type=image_type_to_extension(exif_imagetype($imagePath));   //文件类型</code>
Copy after login
Copy after login

<code>$image = file_get_contents($url);

echo check_image_type($image);

function check_image_type($image)
{
    $bits = array(
        'JPEG' => "\xFF\xD8\xFF",
        'GIF' => "GIF",
        'PNG' => "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a",
        'BMP' => 'BM',
    );
    foreach ($bits as $type => $bit) {
        if (substr($image, 0, strlen($bit)) === $bit) {
            return $type;
        }
    }
    return 'UNKNOWN IMAGE TYPE';
}</code>
Copy after login

<code>$finfo = new finfo(FILEINFO_MIME_TYPE);
var_dump($finfo->file('t.jpg')); // ==> image/jpeg</code>
Copy after login

Use finfo extension

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!