Thursday, 9 August 2018

PHP: Detect If Operating System Is Windows

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:
In the PHP example above:
  1. 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.
  2. 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.
  3. 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:
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

0 comments:

Post a Comment