我有一个与操作系统的CLI交互的PHP脚本,我希望这个脚本能在不同的Linux发行版上运行,所以我必须与不同的Linux风格进行不同的交互以实现某些目标,但是我找不到PHP区分它们的方法。
我试过使用php_uname('s')
和PHP_OS
,他们都返回Linux
;这对我没有任何用处(我在Arch Linux上测试)
我问这个问题,因为-例如-如果我想在Ubuntu中管理一个服务/守护进程,我将使用service
命令,并在Arch中使用systemctl
命令,所以不知道哪个Linux发行版正在运行我的PHP脚本,没有办法我可以处理这样的问题。
我找到了一个灵活的解决方案。这是通过从/etc目录查找发布文件(而不是打印文件内部的实际内容),所以如果我在Arch Linux上运行这个脚本,它将检查/etc
目录中的arch-release
文件,等等其他Linux发行版。
代码如下:
-
PHP不会扫描
/etc
目录,如果你不修改php.ini
文件,使其允许对其进行文件操作(修改open_basedir
选项,通过在末尾添加:/etc/
) -
下面代码中可识别的发行版列表很容易扩展,您所需要的只是发行版的漂亮名称(例如;Ubuntu)及其发布文件的名称(例如。
lsb-release
)。要查看著名linux发行版的完整列表,请点击这里。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通常会返回uname
在控制台中的结果,通常是Linux内核。由于不同的发行版有不同的版本说明方式,我无法给出一个适用于所有版本的明确方法,但是,请阅读以下内容:http://www.cyberciti.biz/faq/find-linux-distribution-name-version-number/
结合php的exec