Current Location: Home> Latest Articles> Correct Use of filetype and file_exists Functions to Avoid Common Mistakes

Correct Use of filetype and file_exists Functions to Avoid Common Mistakes

gitbox 2025-09-28
<?php
// Some unrelated preliminary content
$now = date("Y-m-d H:i:s");
echo "Current time: <span class="hljs-subst">{$now}\n";
<p>// --------------------------------------------<span></p>
<p>/<span class="hljs-comment">/**</p>
<ul data-is-last-node="" data-is-only-node="">
<li>
<p>Correct Use of <code>filetype
  • if (file_exists("data.txt")) {

  • echo "File exists";
    
  • } else {

  • echo "File does not exist";
    
  • }

  • Common mistakes:

    • Ignoring permission issues that lead to false negatives (file exists but returns false).

    1. Proper Use of filetype()


  • filetype() returns the type of a given path as a string, such as:

    • file for a regular file

    • dir for a directory

    • Other types like block, char, fifo, link, socket may appear depending on the system

  • You must ensure the path exists before calling it; otherwise, it will generate a warning. Therefore, it is common to use file_exists() first.

  • Example:

  • $path = "data.txt";

  • if (file_exists($path)) {

  • echo "Type is: " . filetype($path);
    
  • } else {

  • echo "Path does not exist";
    
  • }

  • Common mistakes:

    • Calling filetype() without first checking if the file exists, causing PHP warnings.

    • Misinterpreting the return value of filetype() as a boolean. It actually returns a string such as file or dir.

    1. Best Practices for Combined Use


  • When you need to both check if a path exists and distinguish whether it is a file or directory, you can write:

  • $path = "uploads";

  • if (!file_exists($path)) {

  • echo "Path does not exist";
    
  • } else {

  • $type = filetype($path);
    
  • if ($type === "file") {
    
  •     echo "This is a file";
    
  • } elseif ($type === "dir") {
    
  •     echo "This is a directory";
    
  • } else {
    
  •     echo "Other type: " . $type;
    
  • }
    
  • }

  • Summary


    • file_exists() is used to check if a path exists but does not distinguish between files and directories.

    • filetype() is used to determine the type but must be used only when the path exists.

    • Common mistakes to avoid: ignoring permission issues, misunderstanding return value types, and not checking existence first.

  • Only by correctly understanding and combining these two functions can you avoid common pitfalls in file operations and improve code robustness and reliability.
    */