PHP: Can include a file that file_exists() says doesn't exist

别来无恙 提交于 2020-01-04 13:23:25

问题


In my script, I set the include path (so another part of the application can include files too), check that a file exists, and include it.

However, after I set the include path, file_exists() reports that the file does not exist, yet I can still include the same file.

<?php
  $include_path = realpath('path/to/some/directory');
  if(!is_string($include_path) || !is_dir($include_path))
  {
    return false;
  }
  set_include_path(
    implode(PATH_SEPARATOR, array(
      $include_path,
      get_include_path()
    ))
  );
  // Bootstrap file is located at: "path/to/some/directory/bootstrap.php".
  $bootstrap = 'bootstrap.php';

  // Returns "bool(true)".
  var_dump(file_exists($include_path . '/' . $bootstrap));
  // Returns "bool(false)".
  var_dump(file_exists($bootstrap));

  // This led me to believe that the include path was not being set properly.
  // But it is. The next thing is what puzzles me.

  require_once $bootstrap;
  // Not only are there no errors, but the file is included successfully!

I can edit the include path and include files without providing the absolute filepath, but I cannot check whether they exist or not. This is really annoying as every time a file that does not exist is called, my application results in a fatal error, or at best a warning (using include_once()).

Turning errors and warnings off is not an option, unfortunately.

Can anyone explain what is causing this behaviour?


回答1:


file_exists does nothing more than say whether a file exists (and the script is allowed to know it exists), resolving the path relative to the cwd. It does not care about the include path.




回答2:


Yes Here is the Simplest way to implement this

$file_name = //Pass File name 
if ( file_exists($file_name) )
            {
                echo "Exist";
            }
        else
            {
                echo "Not Exist";
            }


来源:https://stackoverflow.com/questions/2331067/php-can-include-a-file-that-file-exists-says-doesnt-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!