How to get the OS on which PHP is running?

2020-01-25 06:36发布

For building a unix/dos specific script I need to know on which kind of operating system I am.

How do i get this information?
phpinfo(); tells me a lot more and not very clear whether I'm running on unix or not.

9条回答
时光不老,我们不散
2楼-- · 2020-01-25 07:19

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.

查看更多
萌系小妹纸
3楼-- · 2020-01-25 07:19

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.

查看更多
ゆ 、 Hurt°
4楼-- · 2020-01-25 07:24

On php 7.2.0 you can use the PHP_OS_FAMILY constant:

In other PHP version you can use:

/**
* return DOS OR UNIX
*/
function familyOS() {
   return (stripos(PHP_OS, "WIN") === 0)? "DOS" : "UNIX";
}
查看更多
登录 后发表回答