tags:

views:

322

answers:

5

I've got an dynamically-generated PHP file that is included (via include) in other PHP script. When the first one (for some obscure reason) is generated with parse-errors, causes the main script parse-error an stop the execution.

Is there any way to detect parse errors when including a file so I can regenerate dinamically that file?

Thank you in advance

+1  A: 

You can run the command line version of PHP to check the syntax:

php -l filename

If you need to check the syntax from within the PHP script, use the exec() function to call the command line program.

See also the deprecated function php_check_syntax()

Matt Bridges
This is deprecated after 5.0.4
Tom Haigh
Just noticed that...changed my answer.
Matt Bridges
A: 

You could execute (using exec() or similar) php -l file.php and look at the result. It would be slow I would think to do this on every include.

Would it not be better to fix whatever is causing you to generate PHP files which are sometimes invalid?

Tom Haigh
A: 

You could do a file_get_contents and then scan it to see if there are any parse errors.

$contents = file_get_contents($path);
if (stripos($contents, 'Parse error:') !== 0)
{
  // There was a parse error.
} else {
  // There were no parse errors.
}
James Skidmore
won't file_get_contents() just give you php code if $path is a filename ?
Tom Haigh
A: 

I have a script that will go through my code tree and look for syntax errors. Its not very advanced, but the basics of it is

 $cmd="php -l " . $basedir . $dir . "/" . $file;
 $s=exec($cmd,$k);
 if( strstr($s,"No syntax errors detected") ) { include($basedir.$dir."/".$file); }

This runs php -l on the script you are about to include, and if there are no errrors loads it.

ryanday
A: 

By executing shell_exec(), you can see the output as if you executed that file via command line. You can just see if there is an error right here.

<?php
if (strpos(shell_exec('php -l file.php'), 'Syntax Error')) {
    die('An error!');
}
Sean Fisher