PHP Filesystem filetype() Function



The PHP Filesystem filetype() function is used to return the file type of a specified file or directory. This function can return one of seven possible values on success or false on failure.

The possible values are fifo, char, dir, block, link, file, and unknown.

The filetype() can also produce an E_NOTICE message if the stat call fails or if the file type is unknown.

Syntax

Below is the syntax of the PHP Filesystem filetype() function −

string filetype ( string filename )

Parameters

The parameters are needed to use the filetype() function are mentioned below −

Sr.No Parameter & Description
1

filename(Required)

The filename that will be scanned for getting the file type.

Return Value

The function returns one of seven possible values on success or FALSE on failure.

PHP Version

The filetype() function was first introduced as part of core PHP 4 and work well with the PHP 5, PHP 7, PHP 8.

Example

This example will demonstrate the basic usage of PHP Filesystem filetype() function, so we will see the type of the file and directory in the below code.

<?php
   echo filetype("/PhpProject/sample.txt");  // file
   echo "<br>";
   echo filetype("/PhpProject/");  // directory
?>

Output

This will generate the following result −

file
dir

Example

In the below example we will check the file type of a non existent file. Let us see how filetype() function respond to this situation.

<?php
   //Mention the file path
   $filepath = "/PhpProject/nonexistentfile";

   //Print the file type 
   echo filetype($filepath); 

?> 

Output

This will produce the following result −

unknown

Example

In the below example we will check the type of a directory called /PhpProject using filetype() method. If the directory is present it will show the file type, else it will say the directory does not exist.

<?php
   $directory = '/PhpProject';

   if (file_exists($directory)) {
      echo 'The file type is: ' . filetype($directory);
   } else {
      echo 'Directory does not exist.';
   }
?> 

Output

This will create the below output −

The file type is: dir

Example

In the below example we will check the file type of a symbolic link file. Let us see how filetype() function work in this case −

<?php
   // Mention the symbolic link here
   $link = '/PhpProjects/myfile_link.txt';

   if (file_exists($link)) {
      echo 'The file type is: ' . filetype($link);
   } else {
      echo 'Symbolic link does not exist.';
   }
?> 

Output

This will produce the following result −

The file type is: link

Summary

The PHP function filetype() is a helpful tool for managing and processing files, as it may be used to find the type of file or directory.

php_function_reference.htm
Advertisements