PHP Version Number

Different functions and options are always being added to PHP. Although new versions generally don't create much backward compatibility issues it is usually prudent to write production code that you know will work on servers running a slightly older version of the language.

To check the currently used PHP version you can use the function phpversion() or the constant PHP_VERSION. Both the function and the constant return a string that contains the version number. There are a couple of ways in which this information can be used, the first is to take the string and convert into an array using the explode() function. With this array you can then check the minor version number and run code like the following:

$version = explode('.', phpversion());
if ($version[0] >= 5 && $version[0] >= 1 && $version[0] >= 6) {
    // System will work fine, do nothing
} elseif ($version[0] >= 4 && $version[0] >= 4 && $version[0] >= 9) {
    // Include 5.1.6 specific code to plug gaps in legacy system
} else {
    // PHP version is below 4.4.9 
    die('You need to be running PHP v5.1.6 or higher to run this application.');
}

The second, and probably more reliable is to use the version_compare() function. This is a built in PHP function that allows you to do the same thing as above, but will also check for pre-release candidates like version 5.3.0-dev. The function takes three parameters, the first two parameters are required and they are the current PHP version number and the version number being compared to. The third parameter is a string that allows you t run your own comparison on the version numbers.

$version = phpversion();
if (version_compare($version, '5.1.6') >= 0) {
    // System will work fine, do nothing
} elseif (version_compare($version, '4.4.9', '==') == true) {
    // Include 5.1.6 specific code to plug gaps in legacy system
} else {
    // PHP version is below 4.4.9 
    die('You need to be running PHP v5.1.6 or higher to run this application.');
}

What you do in any of these situations is up to you, but at the very least you can always print some form of error that informs the system administrator that they need a higher version of PHP to run the software. It's not ideal, but there comes a point when you have to stop supporting legacy code.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
14 + 6 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.