Coder Perfect

PHP script – how to tell if it’s running on 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 tell what kind of environment I’m in? (Rather than complex system hacks, something PHP would be preferable)

To be clear, the script is run from the command prompt.

Asked by siliconpi

Solution #1

Examine the PHP OS constantDocs value.

On Windows, it will return multiple values such as WIN32, WINNT, or Windows.

Take a look at: PHP OS and php unameDocs: Possible Values:

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

Answered by Sander Marechal

Solution #2

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

    // unix, linux, mac

    // windows

Answered by Ibu

Solution #3

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

It appears to be a little more elegant than the standard response. However, the detection with DIRECTORY SEPARATOR stated before is the fastest.

Answered by Ondřej Bouda

Solution #4

Starting with PHP 7.2.0, the constant PHP OS FAMILY: can be used to determine the current operating system.

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

For a list of possible values, consult the PHP documentation.

Answered by josemmo

Solution #5

Note that PHP OS reports the operating system on which PHP was built, not necessarily the operating system on which it is now executing.

If you’re using PHP >= 5.3 and merely want to know whether you’re on Windows or not, checking whether one of the Windows-specific constants is defined, for example:

$windows = defined('PHP_WINDOWS_VERSION_MAJOR');

Answered by ejn

Post is based on