I have a PHP app "index.php" that, for various reasons, needs to run other PHP scripts by using include_once
on that other script. That other script isn't very stable, so is there some way to do a safe include_once
that won't halt the caller?
i.e.:
<?php
safely_include_once('badfile.php'); // MAY throw syntax error, parse error, other badness
echo "I can continue execution after error";
?>
(I know what a bad idea this can be, etc., rest assured this isn't production-environment stuff.)
PHP allows you to selectively suppress error reporting when you think it might occur with the @ syntax. Thus, if you want to open a file that may not exist and suppress any errors that arise, you can use this: $fp = @fopen($file, $mode);
Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences. Its very simple in PHP to handle an errors.
None of these answers will work. The top-voted one, which says to @include(), will still terminate the first script if there is a parse error in the included file.
You can't eval() it, you can't try/catch it, and every way of calling include or require will terminate all execution in the script.
This question remains OPEN and UNSOLVED.
http://bugs.php.net/bug.php?id=41810
This is a bug in PHP, and this functionality's been missing since at least 2006. They classified the bug as "bogus" because, they claim, includes() and requires() happen at compile-time.
This goes out the window if you are generating the string arguments to include() and/or require() at RUNTIME, or doing an eval() over a string containing code that runs an include().
The only real solution, thought not the most elegant one but works is to call in another php interpretor that parses and execute the script for nothing else than checking if it yields a parse error or a No errors detected message to filter error messages like PHP Parse Error blablabla. like this code does :
<?php
function ChkInc($file){
return file_exists($file) && (substr(exec("php -l $file"), 0, 28) == "No syntax errors detected in");
}
?>
This idea came from gillis' comment to include
function manual page at PHP doc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With