views:

128

answers:

3

I'm looking to run a bit of custom error handling for PHP's parse errors - the type when the syntax is wrong, and you get those white screens of death.

(To be clear, the type that would result when running malformed code as so:

<?php
if () {
?>

)

I had a look at setting a custom error handler, but couldn't get anything to happen.

+2  A: 

Normally you'd use set_error_handler for this, but the docs note this:

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

What you have there is a PARSE_ERROR and is not catachble by this. In the "user comment" sections of the set_error_handler page there is a plethora of solutions to catch all errors, and some say it works and some say it doesn't, so I suggest just going through them and finding if any in fact work.

Paolo Bergantino
Hmm, makes sense. I did read through a few of the ideas, but couldn't find one that worked - or indeed did anything..
Rich Bradshaw
+1  A: 

It isn't a Fatal error as the term is used in PHP. It is a Parse error. This means that PHP cannot understand your code and it thus never comes to execution of the code at all. Therefore you can't catch such errors. If you're sure the code to test does not contain any harmful injections, you can eval it:

if ( !@eval( 'if () {' ) )
{

    echo "An error occured.";

}

But be sure to read advices on how and when to use eval. It can be quite dangerous.

okoman
That's an interesting idea, though I don't really want to actually execute the code. Might end up using this idea in a couple of places though...
Rich Bradshaw
+3  A: 

Another idea: If you have an own root server or just want to execute the script on your local PC you could do the following:

Put the code to test in a new file, say failure.php. In your script (same directory), where you want to check for errors, do it this way:

$path_to_test = 'failure.php';
$result = `php -l $path_to_test`;

Then you have the parse error messages in $result, because the flag -l makes PHP only parse the code. It will never execute anything. You can parse the error messages if any on your own and even get the line numbers out of them.

okoman
Implemented this as part of my site testing. Thanks a lot for the tip!
Rich Bradshaw