Samuel Fullman
Samuel Fullman

Reputation: 1312

check php for parse error without processing

I know that if I have a block of code as follows:

eval($code);

that if the code is not valid php, it will give me an error (and continue on). What I normally do is this:

ob_start();
eval($code);
$err=ob_get_contents(); //none of the code I work with outputs HTML so this only catches errors
ob_end_clean();
if($err){
    //do something
}

however, IF THE CODE IS GOOD, then it will process. Is there any way to determine of code will parse out correctly WITHOUT having it process?

Upvotes: 2

Views: 88

Answers (1)

Grzegorz
Grzegorz

Reputation: 3335

What you can do is the following:

  1. Dump your $code to a temporary file.

  2. Execute php using exec( "php -l temporary_file_name" ) ; - notice '-l' option (lint)

  3. Check the output.

  4. Delete temporary file.

If the output is empty then your code is correct. If the output is non empty then it contains error description.

Here is an example of a code that can do that for you. Notice that sys_get_temp_dir() is for php >= 5.2.1, and you need to use "" or "/tmp" instead if you have older php

function correct( $code, &$outarr ) {
  $tmpfname = tempnam(sys_get_temp_dir(), 'phplint.' ) ;
  file_put_contents( $tmpfname, "<?php " . $code . " ?>" ) ;
  $dummy = exec( "php -l " . $tmpfname . " 2>&1", $outarr , $rv ) ;
  unlink( $tmpfname ) ;
  return ( $rv == 0 ) ;
}

And example of usage:

$code = "wrong=;" ;
if ( !correct( $code, $outarr )) {
  echo "Code is not correct \n" ;
  print_r( $outarr ) ;
}

You can, of course, play with outarr, to display better message or use even other methods to catch output like ob_get_contents()

I hope it will help.

Upvotes: 2

Related Questions