Running a php script with compatibility to php4/php5 installed on host machine

I had to write a php script to do some processing on xml input. I executed the code using this line:

php <script_name>.php

The code was working fine on Mac OSX operating system. So, I checked in the code and later I checked out the code on a linux machine using RHEL 4.6 operating system. When I gave the same command on my linux machine, it showed errors like unknown function. So, I checked the php versions installed on Mac OSX  machine and RHEL machine using the command below.

php -v

The output on Mac OSX was:

PHP 5.3.2 (cli) (built: Aug  7 2010 00:04:41)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

The output on RHEL machine was:

PHP 4.3.9 (cgi) (built: Sep 12 2007 11:09:31)
Copyright (c) 1997-2004 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2004 Zend Technologies

So, the difference in the PHP version was the reason why the code written on Mac OSX which was actually a PHP5 script didn’t run on the RHEL machine which had PHP4 installed. So, I had to do some modifications to the original PHP5 script to create a new PHP4 script which was now running as desired on RHEL machine.

I wanted to run the php script oblivious of the php version installed on the machine on which I am running it.  So, I had to write a shell script which extracted the php version installed on the machine and then select the php script which was compatible with the php version installed on this machine. The script I wrote is below.

# Variables to read php version
php4_version=`php -v | grep "PHP 4"`
php5_version=`php -v | grep "PHP 5"`

# One of the variables length should be exclusively greater than 0
if [ ${#php4_version} -gt 0 ]
 elif [ ${#php5_version} -gt 0 ]
  echo "Error: Unexpected php version"
# Executing the php script
php $file

The script works by extracting the version from ‘php -v’ using ‘grep’ command. On a php4 version machine, php5_version variable would be empty and on a php5 version machine, php4_version variable would be empty. Using this notion, we check on the length of the variable to select the php script which would be compatible with the machine. Then in the last step we execute that php script.

Do let me know of better ways of achieving this result by leaving behind a comment.

5 thoughts on “Running a php script with compatibility to php4/php5 installed on host machine”

Leave a Reply

Your email address will not be published. Required fields are marked *

Notify me of followup comments via e-mail. You can also subscribe without commenting.