PHP script - detect whether running under linux or Windows?

I have a PHP script that may be placed on a windows system or a linux system. I need to run different commands in either case.

How can I detect which environment I am in? (preferably something PHP rather than clever system hacks)

Update

To clarify, the script is running from the command line.


Check the value of the PHP_OS constantDocs.

It will give you various values on Windows like WIN32, WINNT or Windows.

See as well: Possible Values For: PHP_OS and php_unameDocs:

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    echo 'This is a server using Windows!';
} else {
    echo 'This is a server not using Windows!';
}

You can check if the directory separator is / (for unix/linux/mac) or \ on windows. The constant name is DIRECTORY_SEPARATOR.

if (DIRECTORY_SEPARATOR === '/') {
    // unix, linux, mac
}

if (DIRECTORY_SEPARATOR === '\\') {
    // windows
}

if (strncasecmp(PHP_OS, 'WIN', 3) == 0) {
    echo 'This is a server using Windows!';
} else {
    echo 'This is a server not using Windows!';
}

seems like a bit more elegant than the accepted answer. The aforementioned detection with DIRECTORY_SEPARATOR is the fastest, though.


Starting with PHP 7.2.0 you can detect the running O.S. using the constant PHP_OS_FAMILY:

if (PHP_OS_FAMILY === "Windows") {
  echo "Running on Windows";
} elseif (PHP_OS_FAMILY === "Linux") {
  echo "Running on Linux";
}

See the official PHP documentation for its possible values.