Home > Article > Backend Development > PHP function introduction—filetype(): Get the type of file
PHP function introduction—filetype(): Get the type of file
Introduction:
In PHP, the filetype() function is a built-in function used to find the type of a file. It can help us quickly obtain file type information for subsequent processing or judgment. This article will introduce the use of this function in detail and provide corresponding code examples.
Function prototype:
string filetype (string $filename)
Parameter description:
Return value:
Example 1: Get the type of file
$filename = 'example.txt'; $filetype = filetype($filename); if ($filetype !== false) { echo "文件的类型为:" . $filetype; } else { echo "获取文件类型失败!"; }
Example 2: Get all file types in the folder
$dir = 'example_folder/'; $files = scandir($dir); foreach ($files as $file) { if ($file != "." && $file != "..") { $filepath = $dir . $file; $filetype = filetype($filepath); if ($filetype !== false) { echo "文件 {$file} 的类型为:" . $filetype . "<br/>"; } else { echo "获取文件类型失败!"; } } }
In the above code, Example 1 demonstrates how Use the filetype() function to get the type of a file and output it to the page. First, we define a file name (example.txt), and then call the filetype() function to get the type of the file. Finally, determine whether the acquisition is successful by judging whether the return value is false.
Example 2 demonstrates how to get the types of all files in a folder. We use the scandir() function to list all file names in the specified directory, then iterate through these file names, call the filetype() function in each loop to obtain the file type, and output it to the page.
Summary:
The filetype() function is a convenient and practical function that can help us obtain the type information of the file. Through this function, we can process different types of files as needed. In practical applications, we can perform corresponding operations according to the file type, such as scaling or cropping image files, reading and processing text files, etc. I hope this article will be helpful to your study and work!
The above is the detailed content of PHP function introduction—filetype(): Get the type of file. For more information, please follow other related articles on the PHP Chinese website!