Master PHP’s filetype() Function: Quickly Identify File Types
Learn how to use PHP’s built-in filetype() function to determine a file’s type, understand its parameters and return values, and see practical code examples for retrieving a single file’s type and iterating through a directory to list all file types.
In PHP, the filetype() function is a built‑in utility for retrieving a file’s type, returning the type as a string or false on failure.
Function prototype: string filetype ( string $filename ) Parameter: $filename – the name or path of the file to examine.
Return value: Returns the file type as a string if successful; otherwise returns false.
Example 1: Get a file’s type
$filename = 'example.txt';
$filetype = filetype($filename);
if ($filetype !== false) {
echo "File type: " . $filetype;
} else {
echo "Failed to get file type!";
}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 {$file} type: " . $filetype . "<br/>";
} else {
echo "Failed to get file type!";
}
}
}The examples demonstrate using filetype() to obtain a file’s type and output it, first for a single file and then for each file in a directory using scandir() to list entries.
Conclusion
The filetype() function is a convenient tool that helps you identify file types, enabling you to handle different file formats appropriately, such as resizing images or processing text files.
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.
