How to catch error of require() or include() in PHP?

前端 未结 6 1034
甜味超标
甜味超标 2020-12-08 15:33

I\'m writing a script in PHP5 that requires the code of certain files. When A file is not available for inclusion, first a warning and then a fatal error are thrown. I\'d li

6条回答
  •  无人及你
    2020-12-08 16:24

    A better approach would be to use realpath on the path first. realpath will return false if the file does not exist.

    $filename = realpath(getcwd() . "/fileERROR.php5");
    $filename && return require($filename);
    trigger_error("Could not find file {$filename}", E_USER_ERROR);
    

    You could even create your own require function in your app's namespace that wraps PHP's require function

    namespace app;
    
    function require_safe($filename) {
      $path = realpath(getcwd() . $filename);
      $path && return require($path);
      trigger_error("Could not find file {$path}", E_USER_ERROR);
    }
    

    Now you can use it anywhere in your files

    namespace app;
    
    require_safe("fileERROR.php5");
    

提交回复
热议问题