Skip to main content

Quality Assurance on PHP projects - PHPLint

PHP Lint
PHP Lint is probably the easiest way to validate your code on syntax errors, but it's also the most overlooked feature of PHP on command line.

Provides a convenient way to perform only a syntax check on the given PHP code. On success, the text No syntax errors detected in is written to standard output and the shell return code is 0. On failure, the text Errors parsing in addition to the internal parser error message is written to standard output and the shell return code is set to -1.

This option won't find fatal errors (like undefined functions). Use the -f to test for fatal errors too.

Example of detecting failures only
user@machine: $ /usr/bin/php -l /path/to/myfile.php

Example of detecting failures and fatal errors
user@machine: $ /usr/bin/php -lf /path/to/myfile.php

Since this tool also returns numeric return codes, you can use it immediately as a pre-commit hook of your favorite revision control system like Git or Subversion. And with PHP on command line, you can create your own hooks with PHP. 

Example of a Git pre-commit hook taken from Travis Swicegood's article "Don't submit that error" on the PHP Advent pages.

// author: Travis Swicegood

$output = array();
$return = 0;
$php = '/usr/bin/php';

exec('git rev-parse --verify HEAD 2> /dev/null', $output, $return);
$against = $return == 0 ? 'HEAD' : '4b825dc642cb6eb9a060e54bf8d69288fbee4904';

exec("git diff-index --cached --name-only {$against}", $output);

$filename_pattern = '/\.php$/';
$exit_status = 0;

foreach ($output as $file) {
    if (!preg_match($filename_pattern, $file)) {
        // don't check files that aren't PHP

    $lint_output = array();
    exec("{$php} -lf " . escapeshellarg($file), $lint_output, $return);
    if ($return == 0) {
    echo implode("\n", $lint_output), "\n";
    $exit_status = 1;


Example of a SVN pre-commit hook I use myself

 * Script that processes your code before it's committed to a Subversion
 * repository.

 * @var string Contains the path to the repository
$repo = $argv[1];

 * @var string Contains the ID of the transaction
$transaction = $argv[2];

// Define the command line tools here
define('PHP', '/usr/bin/php');
define('SVNLOOK', '/usr/bin/svnlook');
define('GREP', '/usr/bin/grep');
define('AWK', '/usr/bin/awk');

 * Checks for commit messages and sees if they are present. More fine
 * grained validation of commit messages can be provided here. If a
 * correct message was given, the function returns false. In all other
 * cases it will return an error message.
 * @param string $transaction The ID of the transaction
 * @param string $repo The path to the repository
 * @return bool|string
function checkCommitMessage($transaction, $repo)
    $message = false;
    $log = SVNLOOK . " log -t {$transaction} {$repo}";
    $commitMessage = null;
    exec($log, $commitMessage);
    if ('' === (string) $commitMessage[0]) {
        $message = 'Required commit message is missing' . PHP_EOL;
    return $message;

 * Checks the syntax of PHP Code with PHP Lint. If no errors where
 * detected, it will return false. In all other cases, it will
 * return the error messages
 * @param string $transaction The ID of the transaction
 * @param string $repo The path to the repository
 * @return bool|string
function checkSyntax($transaction, $repo)
    $messages = array ();
    $result = null;
    $return = false;
    $changed = SVNLOOK . " changed -t {$transaction} {$repo}|"
             . GREP . " \"^[UA]\"|"
             . GREP . " \"\\.php\$\"|"
             . AWK . " '{print \$2}'";
    exec ($changed, $result);
    foreach ($result as $file) {
       $phpLint = array ();
       $lint = SVNLOOK . " cat -t {$transaction} {$repo} {$file}|"
             . PHP . " -l 2>&1";
       $error = exec ($lint);
       if ('No syntax errors detected in -' === $error) continue;
       $messages[] = "{$file} contains PHP syntax errors";
    if (!empty ($messages)) {
        $return = implode(PHP_EOL, $messages);
    return $return;

 * Checks return values of these pre-commit functions and returns
 * the return code: 0 for no messages and 1 in any other case.
 * @param bool|string The message output of pre-commit functions
 * @return int The exit code
function getExitCodes($message)
    if (false !== $message) {
        file_put_contents('php://stderr', $message);
        return 1;
    return 0;

$exitCodes = array ();
$exitCodes[] = getExitCodes(checkCommitMessage($transaction, $repo));
$exitCodes[] = getExitCodes(checkSyntax($transaction, $repo));

if (in_array(1, $exitCodes)) {

Once you have a pre-commit hook in place, you don't have to worry that you commit code contains errors and might cause a failure for other developers in your team. The revision control system will notify you about any failures.


  1. Great post on quality assurance. PHP Lint is indeed one of those underused tools and SHOULD be rooted in every hobby and enterprise PHP project by means of a pre-commit hook.

    thx for sharing

  2. Think you missed the end pre tag before this line :"Example of a SVN pre-commit hook I use myself"

  3. @NickBelhomme: thanks dude, much appreciated your support in this series.

  4. @Maarten Stolte: thanks for finding it, fixed the issue immediately

  5. That is really good stuff. Thanks for sharing it!



  6. Anonymous18/7/11 14:51

    IDE like "Eclipse" or "Netbeans" are also to do that...

  7. Anonymous25/1/13 14:55

    thanks for share.


Post a Comment

Popular posts from this blog

Speeding up database calls with PDO and iterators

When you review lots of code, you often wonder why things were written the way they were. Especially when making expensive calls to a database, I still see things that could and should be improved.
No framework development When working with a framework, mostly these database calls are optimized for the developer and abstract the complex logic to improve and optimize the retrieval and usage of data. But then developers need to build something without a framework and end up using the basics of PHP in a sub-optimal way.

$pdo = new \PDO( $config['db']['dsn'], $config['db']['username'], $config['db']['password'] ); $sql = 'SELECT * FROM `gen_contact` ORDER BY `contact_modified` DESC'; $stmt = $pdo->prepare($sql); $stmt->execute(); $data = $stmt->fetchAll(\PDO::FETCH_OBJ); echo 'Getting the contacts that changed the last 3 months' . PHP_EOL; foreach ($data as $row) { $dt = new \DateTime('2015-04-…

Deploy Docker containers fast to Microsoft Azure

DEPLOY DOCKER CONTAINERS FAST TO MICROSOFT AZURE It’s hard to ignore the fact thatDockeris a way to move forward for rapid application development, distributed architectures and microservices. For developersDockeroffers great advantages as they can build their containers specifically for the task they work on. They grab a base image of a container, modify it for their purpose and prepare the functionality inside the container. Quality, testing and security teams now have a single instance to look at and ensure all functional and regulatory requirements are met. System engineers now don’t have to worry about providing a system with the required specs as the container is already provisioned for that purpose. But where do you deploy yourDockercontainers? You can set up your existing bare metal infrastructure to allow them to run containers, but this also means you need to learn about securing your container infrastructure, which is not an easy task. Luckily “the cloud” offers container …

PHP Arrays - Associative Arrays or Hash Maps

Associative array or hash maps are listings of key and value pairs with a posibility to nest additional keys and values. An associative array is a very powerful construct within PHP.

In our previous article we discussed simple arrays, which in their turn are indexed associative arrays under the hood. Take the following example:

$array = [

Is in fact an indexed associative array under the hood:

$array = [
0 => 'apple',
1 => 'banana',
2 => 'chocolate',

But associative arrays can be so much more than just an indexed array, and you will find many database operations returning arrays where the fields of a table are the keys in the array while their values are also the values within the array.

$productRowData = [
'product_id' => 1234,
'brand_id' => 321,
'product_name' => 'Our awesome product',
'prodcut_description' => 'This is our most awesome product.&#…