W3docs

filetype()

The filetype() function is a built-in PHP function that returns the type of a file. This function returns the file type as a string.

What is the filetype() Function?

The filetype() function is a built-in PHP function that returns the type of a file as a string. It returns values such as file, dir, fifo, symlink, block, char, or unknown. On failure (e.g., if the file does not exist or lacks read permissions), it returns false.

Here's the basic syntax of the filetype() function:

The PHP syntax of filetype()

filetype(filename);

Where filename is the relative or absolute path to the file to be checked.

How to Use the filetype() Function?

Using the filetype() function is straightforward. Here are the steps to follow:

  1. Call the filetype() function, passing in a relative or absolute path to the file you want to check.
  2. The function will return the file type as a string, or false if the operation fails.

Here's an example code snippet that demonstrates how to use the filetype() function:

How to Use the filetype() Function?

<?php

$filename = './myfile.txt';
$filetype = filetype($filename);
echo "The file $filename is of type $filetype";

In this example, we check the type of the file ./myfile.txt using the filetype() function. We store the result in the $filetype variable and output a message. Note that filetype() requires read permissions for the target file. In production code, always verify that the return value is not false before processing it.

Conclusion

The filetype() function provides a quick way to identify file types in PHP. Remember to handle false returns and ensure your script has the necessary read permissions for reliable results.

Practice

Practice

What does the is_file() function in PHP do?