Last Updated: September 09, 2019
·
2.989K
· banago

Check for PHP syntax errors before Git commit

If you want to do a quick syntax check of a PHP file you can do so from the terminal like this:

php -l filename.php

However, to really rip the power of this, we can use it with Git to check files for errors before we commit them. The little script below goes into the pre-commit Git hook and it check if PHP files to be commited contain errors and if they do, the commit fails.

#!/bin/bash

#loop trough the modified files
for file in $(git diff-index --name-only HEAD); do
    if [ "$(mimetype -b $file)" == 'application/x-php' ]; then
        message=$(php -l $file)
        if [[ $message == Errors* ]]; then
            echo "Commit failed. Please fix errors and recommit."
            exit 1;
        fi        
    fi
done;

Happy hacking!