PHP script - detect whether running under linux or 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.
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
}
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_uname
Docs:
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
echo 'This is a server using Windows!';
} else {
echo 'This is a server not using Windows!';
}
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.