Search code examples
command-line-interfacerequirephp

php cli include_once error


I am writing a php cli script, and my includes and requires are generating errors.

"PHP Warning: include_once(SCRIPT FOLDER): failed to open stream: Inappropriate ioctl for device in SCIPT PATH on line XX"

Im setting the working directory to the location of the script using

chdir(dirname(__FILE__));

and wrote a wrapper function to include files as such (just code fragments):

$this->_path = rtrim(realpath('./'), '/').'/';     
public function require_file($file)
{ 
  if (include_once $this->_path.$file === FALSE)
    $this->fatal_error('Missing config file (config.php)');
}

What am I doing wrong, or missing?


Answer: (can't answer my own question less than 100 rep)

The proper thing to do when comparing return values from include is

if ((include 'file') === FALSE)

doing it in the wrong fashion will evaluate to include '', causing my error.


Solution

  • Well, include_once is a special language construct, not a function. As such you shouldn't try to use a return value from it (like === FALSE). The PHP manual entry on the topic says that "The include() construct will emit a warning if it cannot find a file" so, checking that === FALSE doesn't help your situation.

    My recommendation would be to use a custom error handler that throws exceptions when PHP errors are raised. Then you could wrap your include_once in a try/catch block to handle the exception caused by the invalid include however you like.

    So, for example ...

    function require_file($file)
    { 
      set_error_handler(function($errno, $errstr) { throw new Exception($errstr); });
      try {
        include_once $file;
        restore_error_handler();
        echo 'woot!';
      } catch (Exception $e) {
        echo 'doh!';
      }
    }
    $file = 'invalid_filename.php';
    require_file($file); // outputs: doh!
    

    Note: I use a closure in this example. If you're working with < PHP5.3 you'd need to use an actual function for the error handler.