This is a PHP tutorial on how to check if the operating system is Windows. To do this, we simply check the value of the PHP_OS constant.
The code.
Let’s take a look at the code:
<?php //By default, we assume that PHP is NOT running on windows. $isWindows = false; //If the first three characters PHP_OS are equal to "WIN", //then PHP is running on a Windows operating system. if(strcasecmp(substr(PHP_OS, 0, 3), 'WIN') == 0){ $isWindows = true; } //If $isWindows is TRUE, then print out a message saying so. if($isWindows){ echo 'This operating system is Windows!'; }
In the PHP example above:
- We start off by assuming that the operating system is not Windows. It is up to the rest of our script to prove this assumption wrong.
- We check the first three characters of the PHP_OS constant. If the first three characters are WIN, then we know that PHP is running on Windows.
- Finally, we print out a message for example purposes.
PHP_OS
PHP_OS is a predefined constant that contains a string. This string tells us which operating system PHP was built for. When I print out the PHP_OS constant on my Windows 7 machine, I get the following result:
WINNT
Depending on what your operating system is, you might get results such as:
- WIN32
- WINNT
- Linux
- Windows
- NetBSD
- FreeBSD
- etc
PHP_SHLIB_SUFFIX
You could also check the PHP_SHLIB_SUFFIX constant, which contains the build-platform’s shared library suffix. If PHP is running on a Windows operating system, then this constant will contain the string “dll”. An example using this approach:
//By default, we assume that PHP is not running on windows. $isWindows = false; //If PHP_SHLIB_SUFFIX is equal to "dll", //then PHP is running on a Windows operating system. if(strtolower(PHP_SHLIB_SUFFIX) === 'dll'){ $isWindows = true; } //If $isWindows is TRUE, then print out a message saying so. if($isWindows){ echo 'This operating system is Windows!'; }
Personally, I would stick to checking the PHP_OS constant unless you are running PHP 7.2. or above.
PHP_OS_FAMILY
If you are running PHP 7.2. or above, you can simply check the PHP_OS_FAMILY constant. This constant may contain the following values:
- Windows
- BSD
- Darwin
- Solaris
- Linux
- Unknown
Hopefully, you found this article to be helpful!