1
$code = 'php statement';

// getting perse error
function perse_error_check($code){
 if(eval($code) === "true"){
   return "no perse error"; 
 }

 if(eval($code) === "false"){
  return "perse error found"; 
 }
}


// getting fatal error
function fatal_error_check($code){
.......................................
.......................................
}

Can you help me to complete the second function? Actually I am not sure weather it is possible or not.

Asif Iqbal
  • 1,132
  • 1
  • 10
  • 23
  • 3
    One of the biggest problems with using eval() (after the security risks) is that you can't do any error handling with it – Mark Baker Jan 25 '15 at 20:47
  • 1
    Very simple just don't use it! Never use `evil()` – Rizier123 Jan 25 '15 at 20:48
  • Yikes. Sounds like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What are you trying to do that you thought eval was the solution? Chances are there is a better (and definitely a safer) way. – Brad Christie Jan 25 '15 at 20:48
  • `$code` won't be expanded for evaluation at all if it is single-quoted when passed to `eval()` – Michael Berkowski Jan 25 '15 at 20:49

2 Answers2

1

The following writes the PHP code to another file. It then uses command line execution to parse the file and check for erros:

/* Put the code to be tested in a separate file: */
$code = '<?php echo "Test"; ?>';
file_put_contents('check.php', $code);

/* Parse that file and store the message from the PHP parser */
$x = exec( 'php -l check.php');

/* Check the message returned from the PHP parser */
if(preg_match('/Errors parsing/i',$x))
{
    echo 'The code has errors!';
}
else
{
    echo 'The code looks good!';
}

/* delete the file */
unlink('check.php');

The benefit is that the code doesn't run, it just gets parsed. However I assume you would then write that code to a file and use it... so like others mentioned, be VERY careful. Use things like open_basedir (and test it) to restrict access to specific directories, manually check the code before including it in production... etc.

Frank Forte
  • 2,031
  • 20
  • 19
-2

There is a simple way. Put your PHP code in an another file. For an example: index.php and check.php . Put your PHP code in check.php.

Now in index.php write:

$check_data = file_get_contents("yourhosturl/allotherdirectory/check.php");

if(preg_match("/Fatal error/",$check_data)){
    echo "fatal error found"; 
}
George Cummins
  • 28,485
  • 8
  • 71
  • 90
Asif Iqbal
  • 1,132
  • 1
  • 10
  • 23
  • Be VERY careful. If `$code` has anything malicious, you're now giving full-on access to file system, database, etc. using this. One of the very real dangers of `eval` and executing strings of code. – Brad Christie Jan 25 '15 at 21:30
  • 1
    `$check_data` will just have the PHP code as a string, it will not evaluate it or parse it. See my answer to this question. – Frank Forte Apr 29 '16 at 17:22