How to check PHP syntax from a shell script

Shells

Photo by 500CPM

I really like the philosophy of making small incremental investments by solving frequent problems, and Eric Ries' article on the five whys inspired me to look at my development process afresh.

I edit my PHP code on my MacBook, and then upload it to my EC2 server to test, since there's a lot of data I can't replicate locally. Often there will be a typo in my code, but I don't find out about it until I have uploaded all the files, refreshed the browser, and then checked the server error log. Catching simple typos early would save me a lot of time, so I looked around for an automated solution.

The shell script below is what I ended up with. It runs php -l on all my source files to look for syntax errors, and then runs the upload process if that check passes. I've only tested it on OS X, and you'll need PHP installed locally. You can either cut and paste the code, or download it here.

#!/bin/sh
#
# Pete- Script to upload the PHP source code to the server, checking for syntax errors first
#

# Insert the path to your source directory here
SOURCE_DIRECTORY=
# The path to your ssh key. If you don't have one, remove the -i argument to ssh
SSH_KEY=~/.ec2/id_rsa-pstam-keypair
# Put the username, domain name and path to the remote server's folder
SERVER_PATH=user@yourserver.com:/www/html/

SYNTAX_RE='No syntax errors*'
PHP_FILES=$SOURCE_DIRECTORY/*.php

echo "**Checking PHP syntax**"

ls $PHP_FILES  1>/dev/null  2>/dev/null
case $? in
0)
   set `ls $PHP_FILES`
   for args
    do
     SYNTAX_OUTPUT=`php -l $args`
     if [[ "$SYNTAX_OUTPUT" != $SYNTAX_RE ]]
     then echo "$SYNTAX_OUTPUT"
     exit 1
     fi
    done
    ;;
* ) echo "No files found"
    ;;
esac

echo "**Uploading files**"

scp -i $SSH_KEY $PHP_FILES $SERVER_PATH

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: