Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP script - detect whether running under linux or Windows?

People also ask

How to check operating system in PHP?

php_uname() returns a description of the operating system PHP is running on. This is the same string you see at the very top of the phpinfo() output. 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.

How do I know if a PHP script is running?

Check if a PHP script is already running If you have long running batch processes with PHP that are run by cron and you want to ensure there's only ever one running copy of the script, you can use the functions getmypid() and posix_kill() to check to see if you already have a copy of the process running.


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.


Note that PHP_OS reports the OS that PHP was built on, which is not necessarily the same OS that it is currently running on.

If you are on PHP >= 5.3 and just need to know whether you're running on Windows or not-Windows then testing whether one of the Windows-specific constants is defined may be a good bet, e.g.:

$windows = defined('PHP_WINDOWS_VERSION_MAJOR');

The php_uname function can be used to detect this.

echo php_uname();