Wednesday, 27 June 2012

Detecting PHP versions


This is a quick post about detecting what version of PHP your server is currently running, why would this be important? Well there are quite a few PHP functions which only work from a certain version onwards or work different from one version to the next. I encountered this while making a few amends to the way sessions are regenerated in the secure PHP login class I've been building with the session_regenerate_id() function.

How to detect versions

There is more than one way to do this but I'm just going to cover the method which will work in PHP 4 & 5 and tell you exactly which version is being used. The code is below:

if(strnatcmp(phpversion(), '5.0.0') >= 0)
{
echo '5 or higher';
}
else
{
echo '4 or lower';
}

The strnatcmp() function compares two strings to each other using a more 'natural' human method rather than the way computers would normally do. For example a computer would normally put the number "11" before the number "2" but using strnatcmp() it realises an eleven is an eleven and not two ones next to each other.

phpversion() does pretty much what it says, it gets the PHP version in use on the server. It does have a parameter which you can pass to it which I think is to do with finding out about extensions (or their versions) installed on the server. I can't say for certain about that parameter though as I didn't really look into it, it's not relevant to finding out which version of PHP you're using though.

Alternative method

I thought I'd briefly put this down, you can use PHP_MAJOR_VERSION to get the major version in use (5, 6 etc), PHP_MINOR_VERSION which gets the minor version and then PHP_RELEASE_VERSION to get the release. These only work from PHP 5.2.7 upwards though which is why I'm mentioning it at the end so you know it for future reference but I don't think it is very useful at the moment.

To understand the version numbers a bit better think of it like this, when you see a PHP version release it is normally something like 5.2.3. The first number is the major version, the second is the minor version and the third is the release, I won't cover what these all really mean here as it's not really relevant to this post.

Further reading

No comments:

Post a Comment