Detect Required PHP Version

If you write and/or use open source software, you know that running an up to date version of PHP is a must. This can be a problem sometimes, like if you are running on a host that doesn’t run the most up to date version of PHP. Another scenario would be running Ubuntu and installing PHP from the main repository which at the moment is still on the 5.3.x branch even though 5.4 has been out for a while and 5.5 has recently been released.

As an open source contributor, you could rely on your users knowing what version they are running but let’s be honest, most folks never bother to check the README. To help take the guesswork out of it, you could add a sanity check in your code to ensure that they are running a version that’s compatible with your code.

Let’s use file_get_contents as an example. Prior to PHP 4.3.0 the function didn’t even exist. If you wanted to make sure the user was running 4.3 or above, you would do this:

if (version_compare(phpversion(), '4.3.0', '<'))
{
	throw new Exception('Sorry bub, your PHP is too old'
}

Not much to it, but you will need to be mindful of when certain syntax was introduced (which is always available on http://php.net

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.