How to accurately determine the file type in php without using the extension

墨辰丷
Release: 2023-03-27 17:52:01
Original
1583 people have browsed it

This article mainly introduces the method for PHP to accurately determine the file type without using the extension. It involves the finfo_file method in PHP and the related operating skills of binary stream for file types. Friends in need can refer to this article

The example describes how PHP can accurately determine the file type without using the extension. Share it with everyone for your reference, the details are as follows:

The first method

Through php's finfo_file()

$handle=finfo_open(FILEINFO_MIME_TYPE);//This function opens a magic database and returns its resource. 
$fileInfo=finfo_file($handle,'./test.txt');// Return information about a file
finfo_close($handle);
print_r($fileInfo);
echo '==========="\n"';
Copy after login

Also

finfo_buffer: Return information about a string buffer
finfo_close: Close fileinfo resource
mime_content_type:Detect MIME Content-type for a file (deprecated)

Second method

Get file content through binary stream

$fp=fopen('test.txt','r')///实际是image/png
$bin = fread($fp, 2); //只读2字节
fclose($fp);
$str_info = @unpack(“C2chars”, $bin);//Unpack data from binary string
$type_code = intval($str_info['chars1'].$str_info['chars2']);// Get the integer value of a variable
$file_type = ”;
switch ($type_code) {
case 7790:
$file_type = 'exe';
break;
case 7784:
$file_type = 'midi';
break;
case 8075:
$file_type = 'zip';
break;
case 8297:
$file_type = 'rar';
break;
case 255216:
$file_type = 'jpg';
break;
case 7173:
$file_type = 'gif';
break;
case 6677:
$file_type = 'bmp';
break;
case 13780:
$file_type = 'png';
break;
default:
$file_type = 'unknown';
break;
}
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

PHP Analysis of tips for using file locks, mutex locks, and read-write locks in programs _php skills

##PHPSummary of several ways to try program concurrency in programming_php skills

##PHP Use the AdminLTE template to write the website backend interface in the Laravel framework_php tips

The above is the detailed content of How to accurately determine the file type in php without using the extension. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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