2

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?

2
  • 1
    nl3.php.net/manual/en/function.php-check-syntax.php#87762 Commented Dec 31, 2013 at 18:31
  • php_check_syntax() is PHP 5 <= 5.0.4, so only an option if you're using a version of PHP where we'd be screaming at people to upgrade immediately if they were using it Commented Dec 31, 2013 at 18:52

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.