How to get the OS on which PHP is running?
PHP Does not provide any function to get the name of the distribution, php_uname
is similar to Linux command uname
, does not provide any info about the distribution itself.
Neither php_uname
nor PHP_OS
give sufficient info. about the distribution but the OS type (e.g. Linux / Windows).
I think the best way to know what is the running OS/distribution is to read /etc/os-release
, the good thing is this file has read permission for all system users and the bad thing is it may not work on shared hosting.
Here I wrote a very simple PHP function which reads and convert os-release
to an array:
function getOSInformation()
{
if (false == function_exists("shell_exec") || false == is_readable("/etc/os-release")) {
return null;
}
$os = shell_exec('cat /etc/os-release');
$listIds = preg_match_all('/.*=/', $os, $matchListIds);
$listIds = $matchListIds[0];
$listVal = preg_match_all('/=.*/', $os, $matchListVal);
$listVal = $matchListVal[0];
array_walk($listIds, function(&$v, $k){
$v = strtolower(str_replace('=', '', $v));
});
array_walk($listVal, function(&$v, $k){
$v = preg_replace('/=|"/', '', $v);
});
return array_combine($listIds, $listVal);
}
This function prints something like this:
Array
(
[name] => Ubuntu
[version] => 16.04.2 LTS (Xenial Xerus)
[id] => ubuntu
[id_like] => debian
[pretty_name] => Ubuntu 16.04.2 LTS
[version_id] => 16.04
[home_url] => http://www.ubuntu.com/
[support_url] => http://help.ubuntu.com/
[bug_report_url] => http://bugs.launchpad.net/ubuntu/
[version_codename] => xenial
[ubuntu_codename] => xenial
)
Held og lykke [1] ;-)
[1] Danish phrase means good luck.
Just bear in mind that PHP_OS
actually contains the platform on which PHP was built. This may not be the same platform as that on which it is deployed. Therefore php_uname('s')
is more reliable.
As of PHP 7.2.0 we have a new Predefined Constant to get the operating system family i.e. PHP_OS_FAMILY. It returns a string Either of 'Windows', 'BSD', 'OSX', 'Solaris', 'Linux' or 'Unknown'.
PHP has many predefined constants that are often useful.
Here, PHP_OS
is the one you are looking for.
For instance, on my current machine, this code :
var_dump(PHP_OS);
Gives :
string 'Linux' (length=5)
You have some examples and comparisons with what the php_uname
function can get you on the manual page of php_uname
; for instance (quoting) :
<?php
echo php_uname();
echo PHP_OS;
/* Some possible outputs:
Linux localhost 2.4.21-0.13mdk #1 Fri Mar 14 15:08:06 EST 2003 i686
Linux
FreeBSD localhost 3.2-RELEASE #15: Mon Dec 17 08:46:02 GMT 2001
FreeBSD
Windows NT XN1 5.1 build 2600
WINNT
*/
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
echo 'This is a server using Windows!';
} else {
echo 'This is a server not using Windows!';
}
That page also says :
For the name of just the operating system, consider using the
PHP_OS
constant, but keep in mind this constant will contain the operating system PHP was built on.