How does php determine the file type of a binary stream?

Source: Internet
Author: User
I recently used the following method to determine the file type: download the file and get the file stream-& amp; gt; stored on the hard disk-& amp; gt. However, this seems a lot more than that. can you determine the file type without saving the disk after file_get_contents? {Code...} I recently used the following method to determine: download an object, get a file stream-> store it on a hard disk-> determine the file type.
However, I think this seems like a lot of work. can I file_get_contents()Can I determine the file type without saving the disk?

$ Image = file_get_contents ($ url); file_put_contents ($ imagePath, $ image); // save the image stream to the image directory on the server $ type = image_type_to_extension (exif_imagetype ($ imagePath )); // file type

Reply content:

I recently used the following method to determine: download an object and get the file stream-> store it on the hard disk-> determine the file type.
However, I think this seems like a lot of work. can Ifile_get_contents()Can I determine the file type without saving the disk?

$ Image = file_get_contents ($ url); file_put_contents ($ imagePath, $ image); // save the image stream to the image directory on the server $ type = image_type_to_extension (exif_imagetype ($ imagePath )); // file type

$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';}

$finfo = new finfo(FILEINFO_MIME_TYPE);var_dump($finfo->file('t.jpg')); // ==> image/jpeg

Use finfo extension

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.