Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check a PHP file for syntax errors [duplicate]

I'm attempting to build an auditing feature into my application that will check for various code quality issues.

One of the things I would like to do is check certain PHP files for syntax errors. I was going to use php_check_syntax() but it has been removed in PHP 5.0.5.

I've tried using exec() statements but it isn't outputting anything. I've added a date to make sure exec() is working:

<?php

error_reporting(E_ALL | E_NOTICE | E_STRICT | E_WARNING);
ini_set('display_errors', 1);

$output = 'before';
var_dump($output);
var_dump(exec('php -l ' . __FILE__, $output));
var_dump($output);
var_dump(exec('date', $output));
var_dump($output);

Output:

string 'before' (length=6)
string '' (length=0)
array (size=0)
  empty
string 'Thu Feb  6 10:42:35 PST 2014' (length=28)
array (size=1)
  0 => string 'Thu Feb  6 10:42:35 PST 2014' (length=28)

How can I check a PHP file for syntax errors in PHP?

like image 491
Steve Robbins Avatar asked Sep 06 '25 03:09

Steve Robbins


2 Answers

check web-server configuration. places like this: disable_functions="". after var_dump($output) starts to return an array check for errors in array to eliminate further errors like correct path to php.

use this to eliminate some other possibilities:

$output="just before exec";
var_dump($output);
exec('php -l /path/to/file.php', $output);
var_dump($output);

p.s. may be used like

echo exec('php -l /path/to/file.php');

Upd: Updated question shows exec works. It may be your *nix like platform hides the error output. a way to redirect it to add to the command 2>&1 it will redirect error output into standard output

$to_run = '/path/to/bin/php -l /path/to/file 2>&1';
$output ="" ; //init
var_dump(exec($to_run, $output));

if you have root access on the platform you may even use tools like strace to debug some complicated cases.

'/path/to/bin/strace -o/path/to/strace.log php -l /path/to/file.php'

UPD: var_dump(exec('php -l ' . FILE .' 2>&1', $output)); // error redirection for a unix platform

like image 177
Konstantin Ivanov Avatar answered Sep 07 '25 19:09

Konstantin Ivanov


Here's a Unix bash script you could use to syntax check all .php files in folder and subfolder:

find . -iname '*.php' -exec php -l '{}' \; | grep '^No syntax errors' -v  | less

Source: https://gist.github.com/Fake51/865603

like image 30
eduardomozart Avatar answered Sep 07 '25 21:09

eduardomozart