phpfile-exists

file_exists() works on string but not string variable


I have problem with function file_exists() in PHP. Result of code below is always "Exists on string", but in my opinion it should print two messages.

$file = 'test_file.txt';
  if (file_exists($file)){
       echo 'Exists on variable';
  }
  if (file_exists('test_file.txt'){
       echo 'Exists on string';
  }

Solution

  • is_file recommended to use to verify files and inconvenience can be for your routes, change

    $file = $_SERVER['DOCUMENT_ROOT'].'/mysite/test_file.txt';
    

    is_file and file_exists are two native PHP functions that can be used to verify whether a particular file exists or not. Although their names are fairly descriptive, you should know that:

    1. is_file returns true only if the path to the last function is actually an existing file.
    2. file_exists returns true whether the past is a file path as a valid directory (use is_dir if you want to specifically check if a path is a directory but not a file).

    This difference is very important. If your goal is not only files and directories is_file is your function. If you want to check a directory or a file indifferently choose file_exists

    example:

    $file ='mysite/public_html/folder/file.php';
    
    $directory ='/mysite/public_html/folder/';
    
    
    $exists = is_file( $file );//return true
    
    $exists = is_file( $directory ); //return false
    
    $exists = file_exists( $file );//return true
    
    $exists = file_exists( $directory ); //return true