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.

php Courses
php Courses
php Courses
Master PHP’s filetype() Function: Quickly Identify 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPCode Examplesfile-handlingfiletype
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.