Well, I have run into a bit of a pickle here. I am needing to check some PHP for syntax errors. I noticed this bit that needs to run from the commandline:
php -l somefile.php
However, is there a way to run this from within a PHP file itself? I've been looking and have think that I can use parse_str
function somehow to accomplish this by entering it into a $_GET, but can't quite understand how this works.
Someone else told me to use 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 had an eval($code)
working, but don't think I should run the script if there are PHP syntax errors.
Any help on this is greatly appreciated, as always!
The quickest way to display all php errors and warnings is to add these lines to your PHP code file: ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); The ini_set function will try to override the configuration found in your php. ini file.
Basic PHP Syntax A PHP script can be placed anywhere in the document. The default file extension for PHP files is " .php ". A PHP file normally contains HTML tags, and some PHP scripting code.
I use token_get_all
for this. I have some PHP code in the db. Before saving, I do
function is_valid_php_code_or_throw( $code ) {
$old = ini_set('display_errors', 1);
try {
token_get_all("<?php\n$code", TOKEN_PARSE);
}
catch ( Throwable $ex ) {
$error = $ex->getMessage();
$line = $ex->getLine() - 1;
throw new InvalidInputException("PARSE ERROR on line $line:\n\n$error");
}
finally {
ini_set('display_errors', $old);
}
}
Works like a charm. Syntax only. No missing variables, type incompayibility etc.
InvalidInputException
is my own. You can make it anything, or return a bool, or handle the exception yourself.
I'm not sure if display_errors
is necessary. It was at some point.
It is safer to check the return status of php -l
$fileName = '/path/to/file.php';
exec("php -l {$fileName}", $output, $return);
if ($return === 0) {
// Correct syntax
} else {
// Syntax errors
}
See this fiddle to see it in action
You could simply do shell_exec()
like this:
$output = shell_exec('php -l /path/to/filename.php');
This gives you the output of the command line operation in the string $output
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With