Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string is valid PHP code [duplicate]

I want to do:

$str = "<? echo 'abcd'; ?>";
if (is_valid_php($str)){
   echo "{$str} is valid";
} else {
   echo "{$str} is not valid PHP code";
}

Is there a simple way to do the is_valid_php check?

All I can find is online php syntax checkers and command-line ways to check syntax, or php_check_syntax which only works for a file, and I don't want to have to write to a file to check if the string is valid.

I'd rather not use system()/exec() or eval()

Related Question - It's old, so I'm hoping there's something new

Other Related Question - all the options (as far as I could tell) either are no longer supported or use command line or have to check files (not strings)

I don't need a full-fledged compiler or anything. I literally only need to know if the string is valid PHP code.

EDIT: By valid php code, I mean that it can be executed, has no compiler/syntax errors, and should contain only PHP code. It could have runtime errors and still be valid, like $y = 33/0;. And it should contain only PHP... Such as, <div>stuff</div><? echo "str"; ?> would be invalid, but <? echo "str"; ?> and echo "$str"; would be valid

like image 366
Reed Avatar asked Sep 16 '26 22:09

Reed


1 Answers

You could pipe the string to php -l and call it using shell_exec:

$str1 = "<?php echo 'hello world';";
$str2 = "<?php echo 'hello world'";
echo isValidPHP($str1) ? "Valid" : "Invalid"; //Valid
echo isValidPHP($str2) ? "Valid" : "Invalid"; //Inalid

function isValidPHP($str) {
    return trim(shell_exec("echo " . escapeshellarg($str) . " | php -l")) == "No syntax errors detected in -";
}

Just had another idea... this time using eval but safely:

test_code.php

$code = "return; " . $_GET['code'];
//eval is safe here because it won't do anything
//since the first thing we do is return
//but we still get parse errors if it's not valid
//If that happens, it will crash the whole script, 
//so we need it to be in a separate request
eval($code); 
return "1";

elsewhere in your code:

echo isValidPHP("<?php echo \"It works!\";");

function isValidPHP($code) {
    $valid = file_get_contents("http://www.yoursite.com/test_code.php?" . http_build_query(['code' => $code]));
    return !!$valid;
}
like image 80
dave Avatar answered Sep 19 '26 11:09

dave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!