Using PHP filetype() Function to Determine File Types
This article explains the PHP filetype() function, its prototype, parameters, return values, and provides two practical code examples—one for retrieving a single file's type and another for listing the types of all files in a directory—helping developers handle files efficiently.
In PHP, the filetype() function is a built‑in function used to determine the type of a file, returning the file type information quickly for further processing or decision making.
Function prototype: string filetype ( string $filename ) Parameter: $filename – the name or path of the file to be examined.
Return value: If the file type is successfully identified, the function returns its type as a string; otherwise it returns false.
Example 1: Get a file’s type
$filename = 'example.txt';
$filetype = filetype($filename);
if ($filetype !== false) {
echo "文件的类型为:" . $filetype;
} else {
echo "获取文件类型失败!";
}This example defines a file name ( example.txt), calls filetype() to obtain its type, and echoes the result if the call does not return false.
Example 2: Get types of all files in a directory
$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 "获取文件类型失败!";
}
}
}This example lists all entries in example_folder/ using scandir(), iterates over each file (skipping . and ..), calls filetype() for each path, and outputs the type or an error message.
Summary: The filetype() function is a convenient tool for retrieving file type information in PHP, enabling developers to handle different file types appropriately—such as resizing images or processing text files—based on the returned type.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
