From inside my index.php file, say, I'd like to check if another PHP file executes without error (and include it, if so), and if it does in fact fail and returns a fatal error, I'd obviously like to not include it. Any suggestions? Thanks...
-
do you really need include? If not, and you're ok with executing the script without sharing any variables/functions aside from those you explicitly pass to it, this is very possible.goat– goat2012-11-05 00:41:23 +00:00Commented Nov 5, 2012 at 0:41
-
Actually no, I don't need to include it after the fact ... I really just need a function that checks if a PHP file results in a fatal error, and returns TRUE if so, and FALSE if not...Matt Payne– Matt Payne2012-11-05 00:43:56 +00:00Commented Nov 5, 2012 at 0:43
3 Answers
You may use -l parameter of php CLI:
php -l filename.php
and parse the output.
$o = `php -l filename.php`;
if (strpos($o, 'No syntax errors detected') !== false) {
echo 'No errors';
} else {
echo 'There are errors';
}
Comments
You probably don't want to run the second file separately. That said, you can do one of two things...
1.) if you really want to use it as an include that executes separately you could call it with something such as CURL and have it output either the expected result or a failure message that would then be read and acted on accordingly.
2.) Include your function/class/etc execution in a try/catch statement to properly handle any errors encountered. http://php.net/manual/en/language.exceptions.php might help you a little more with this method.
Comments
This runs the script as a separate process, with no shared variables/functions/state/scope etc...
$cmd = 'php file.php';
exec($cmd, $ar, $exit_status);
$wasFatal = $exit_status == 255;
There's a real good chance it gets run with a php.ini that's different than whatever your webserver php.ini is, so expect differences in config and maybe even php version.