Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP robust include to handle errors?

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.)

like image 623
erjiang Avatar asked Oct 06 '09 18:10

erjiang


People also ask

How to suppress errors in PHP?

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);

What is the purpose of Error Handling in PHP explain with suitable example?

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.


2 Answers

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().

like image 121
sneak Avatar answered Sep 17 '22 01:09

sneak


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.

like image 33
Graben Avatar answered Sep 19 '22 01:09

Graben