Categories
PHP

Check File Type (whether a file is a directory or a file)

How to check the type of a file. For example, check whether the provided file name is a directory, a file, or a symbolic link.

The following functions take a filename (for example file.txt, /home/file.txt, ../file.txt, etc.), so the files do not have to be opened before you use these functions. If the filename is a relative filename, it will be checked relative to the current working directory.

Note: The results of the above functions are cached in order to provide faster performance. You can clear the cache with the clearstatcache() function.

filetype()

<?php
 //Syntax
 filetype(string $filename): string|false

The filetype() function returns the type of file given in path. The possible types are:

  • block – Space reserved by the filesystem on the disk.
  • char – A special type.
  • dir – The path is a directory.
  • fifo – A special file, also called a named pipe.
  • file – The path is a regular file.
  • link – The path is a symbolic link.
  • unknown – The type could not be determined.

Example: Determine the type of given path:

<?php
 echo filetype('/home/htdocs');
 // Prints: dir

 echo filetype('/home/htdocs/log.txt');
 // Prints: file

is_dir()

<?php
 //Syntax
 is_dir(string $filename): bool

The is_dir() function returns true if the given filename exists and is a directory; otherwise, returns false.

Example: Check whether the filename is a directory

<?php
 if ( is_dir('/home/htdocs') )
  echo 'dir';
 else
  echo 'not a dir';
 //Prints: dir

 if ( is_dir('/dir-not-exits/dir') )
  echo 'dir';
 else
  echo 'not a dir';
 //Prints: 'not a dir';

is_file()

<?php
 //Syntax
 is_file(string $filename): bool

The is_file() function returns true if the path exists and is a file; otherwise, it returns false.

Example: Check whether the filename is a file

<?php
 if ( is_file('file.txt') )
  echo 'file';
 else
  echo 'not a file';
 //Prints: file

 if ( is_file('/file-not-exits/file.txt') )
  echo 'file';
 else
  echo 'not a file';
 //Prints: 'not a file';
<?php
 //Syntax
 is_link(string $filename): bool

The is_link() function returns true if the filename exists and is a symbolic link otherwise, returns false.

Example: Check whether the filename is a symbolic link

<?php
 $filename = '/home/slink';
 if ( is_link($filename) )
   echo 'link';
 else
  echo 'not a link';
 //Prints: link

is_uploaded_file()

<?php
 //Syntax
 is_uploaded_file(string $filename): bool

The is_uploaded_file() function returns true if the file exists and was uploaded to the web server via an HTML form. For more information, see How to upload and move files safely.


Working with Files in PHP: