I have a PHP script that interacts with OS's CLI, and I'm expecting this script to run on different Linux distributions, so I have to interact with different Linux falvours differently to achieve something, but I couldn't find a way for PHP to differentiate between them.
I've tried using php_uname('s')
and PHP_OS
they both return Linux
; which isn't any useful for me(I was testing on Arch Linux)
I'm asking this question, because -for example- if I wanted to manage a service/daemon in Ubuntu I'll use the service
command , and in Arch ill be using the systemctl
command, so without knowing which Linux distro is running my PHP script there's no way I can deal with such problems.
I found a flexible solution to this issue. Which is by looking-up the release file from the /etc directory(instead of printing what's actually INSIDE the file), so if I'm running this script on Arch Linux, it'll check for arch-release
file in /etc
directory, and so on for other Linux distros.
Here's the code:
IMPORTANT NOTES:
PHP won't scan /etc
directory if you don't modify php.ini
file and make it allowed to do file operations on it(modify open_basedir
option, by adding :/etc/
to the end.)
The list of recognizable distros in the following code is easily extensible, all you need is the pretty name of the distro(e.g. Ubuntu) and the name of its release file(e.g. lsb-release
). For a complete list of famous linux distros, click here.
function getLinuxDistro()
{
//declare Linux distros(extensible list).
$distros = array(
"Arch" => "arch-release",
"Debian" => "debian_version",
"Fedora" => "fedora-release",
"Ubuntu" => "lsb-release",
'Redhat' => 'redhat-release',
'CentOS' => 'centos-release');
//Get everything from /etc directory.
$etcList = scandir('/etc');
//Loop through /etc results...
$OSDistro;
foreach ($etcList as $entry)
{
//Loop through list of distros..
foreach ($distros as $distroReleaseFile)
{
//Match was found.
if ($distroReleaseFile === $entry)
{
//Find distros array key(i.e. Distro name) by value(i.e. distro release file)
$OSDistro = array_search($distroReleaseFile, $distros);
break 2;//Break inner and outer loop.
}
}
}
return $OSDistro;
} }
PHP uname will usually return what uname
would in console, which is usually the Linux kernel. Since different distributions have different ways of telling their version, I cannot suggest a deffinitive method for all of them, however, have a read at this: http://www.cyberciti.biz/faq/find-linux-distribution-name-version-number/
Combine that with php's exec
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With