📅 September 24, 2016
In PHP, we can use php_uname to grab information about the operating system that the server is running on.
echo php_uname(‘s’) will give the name of the OS, but this is a general name. When executed from a server running Xubuntu, it returns the string “Linux.” Is this Ubuntu, Kubuntu, Xubuntu, Linux Mint, or…what?
What if we want to get the specific Linux distribution? Is this possible from PHP without performing host OS system calls or executing Bash scripts? Yes.
“Why not read the /etc/lsb-release or /etc/os-release files on the Linux host?”
This works, but they only provide Ubuntu-related strings for Ubuntu-related distributions. Other distributions, such as Linux Mint, will return Linux Mint strings, but not Xubuntu. Xubuntu will identify itself as Ubuntu to PHP.
user@user:~$ cat /etc/os-release NAME="Ubuntu" VERSION="16.04.1 LTS (Xenial Xerus)" ID=ubuntu ID_LIKE=debian PRETTY_NAME="Ubuntu 16.04.1 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/" UBUNTU_CODENAME=xenial
Shown above are the contents of /etc/os-release running on Xubuntu. Notice that there is no information that will help us identify the Xubuntu distribution.
Look for /etc/xdg/xdg-xubuntu
One trick that works well for me is to test to see if Xubuntu-specific files and directories are present on the system using the is_dir() and file_exists() functions.
The key is to look for files or directories unique to Xubuntu.
Checking to see if /etc/xdg/xdg-xubuntu exists usually works well because this is a system directory present on Xubuntu and not likely to be removed.
<?php if (is_dir('/etc/xdg/xdg-xubuntu')) // Server is running on Xubuntu distribution else // Not Xubuntu. ?>
I chose /etc/xdg/xdg-xubuntu/ because it was unique among the distributions I tried. Is it 100% fool-proof? Probably not, so expand and perform additional checks as needed.
Xubuntu offers other specific files and directories, but I find that this is usually reliable. I would recommend avoiding user-changeable/installable files, such as Xubuntu wallpapers and the xfce4 directories, because users can change them or install XFCE under other distributions (Ubuntu/Kubuntu) which can fool PHP.
Once the correct distribution has been determined, we can then rely upon lsb-release/os-release/php_uname to obtain the version, machine type, Ubuntu codename, and more.