How to check PHP syntax from a shell script


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.

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

# Insert the path to your source directory here
# The path to your ssh key. If you don't have one, remove the -i argument to ssh
# Put the username, domain name and path to the remote server's folder

SYNTAX_RE='No syntax errors*'

echo "**Checking PHP syntax**"

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

echo "**Uploading files**"


Leave a Reply

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

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: