PHP has several different ways to display the currently used version, but what is the best way, and how do you get the PHP version?
PHP version solution
The quickest way and solution to find out what version of PHP is installed is using the command line. If you fire up a terminal and run the following command, PHP will display the current installed version.
$ php -v
Getting the PHP version in a script
Luckily, we don't just have to rely on the command line to find out the version. PHP comes packed with constant variables, which get populated with data at runtime. If you're looking to find the version of PHP within a script you can use the following constant.
PHP_VERSION
And we can display it on screen like so.
echo PHP_VERSION;
PHP version content isn't always useful
When running PHP in a docker container, some Linux and Windows machines, the PHP version includes the operating system build numbers. If you're thinking of outputting this to screen or doing something against it, you'll have to regex out the things we don't want.
$ php -v
PHP 8.1.12-1+0~20240517204500.45+buster~1.gbp076afd (cli) (built: May 17 2024 20:45:00) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.1.12, Copyright (c) Zend Technologies
We can do one better when it comes to finding out the PHP version and avoid the issue above, by a combination of the major, minor, and release php version constant.
PHP_MAJOR_VERSION
PHP_MINOR_VERSION
PHP_RELEASE_VERSION
This is a safer and more accurate way to display/use the PHP version within our PHP scripts. This will output whatever your version is. In our case, it's the latest version of PHP.
echo PHP_MAJOR_VERSION . "." . PHP_MINOR_VERSION . "." . PHP_RELEASE_VERSION;
# Outputs
8.3.7
Compare two version strings in PHP
If you want to compare the server version to your script version of PHP you can use version_compare
.
version_compare();
It will return 0 if both (left and right) are the same, 1 if the second is lower, or -1 if not.
var_dump(version_compare(PHP_VERSION, '8.3.0') >= 0);
You can read more about the latest version of PHP 8.3.