Check for PHP syntax errors?

Ok, I ran into a little pickle. I need to check some PHP errors for syntax errors. I noticed this bit that needs to be run from the command line:

php -l somefile.php

However, is there a way to run this from the PHP file itself? I looked and think that I can somehow use the parse_str function to do this by entering it in $ _GET, but I can’t understand how this works.

Someone else told me to use the token_get_all() php function to determine this.

But I can’t figure out how to do this with any approach? Can anyone here give me some sample code to get started, perhaps? I don't think using eval() is the way to go, although I worked with eval($code) , but I don't think I should run the script if there are PHP syntax errors.

Any help on this is greatly appreciated, as always!

+8
php syntax-error token
source share
6 answers

You can simply do shell_exec() as follows:

 $output = shell_exec('php -l /path/to/filename.php'); 

This gives you the result of a command line operation on the $output line.

+5
source share

Safer to check php -l return status

 $fileName = '/path/to/file.php'; exec("php -l {$fileName}", $output, $return); if ($return === 0) { // Correct syntax } else { // Syntax errors } 

See this script to see it in action.

+2
source share

php_check_syntax should do the trick. If you are using PHP> = 5.05, see the first comment in the comments section for implementation.

+1
source share

Why use a shell at all?

 function syntax_is_valid($code) { try { @eval($code); } catch (ParseError $e) { return false; } return true; } 

Alternatively, use $e->getMessage() for more information.

+1
source share

I would do it like this:

 $php_file = 'The path to your file'; if(substr(`php -l $php_file`, 0, 16) == 'No syntax errors') { // Correct syntax } else { // Error } 
0
source share

You can use exec to check for syntax errors.

 $tempFile = path/of/file $syntaxParseError = strpos(exec('php -l '.$tempFile), 'No syntax errors detected') === false;` 

Unfortunately, this will not give you the line number or will notify you of the error. To do this, you either need to install a static analyzer on your server. Is there a static code analyzer [for example, Lint] for PHP files? or write your own parser.

NB. token_get_all() will not determine anything by itself, but it is a useful function to create a parser.

0
source share

All Articles