How to test if your server is running Windows from PHP

- by

If we’re executing shell commands via PHP we need to know if the server is running Windows or Linux. Thanks to a magic constant in PHP we can find out like this:

echo PHP_OS;

This will give us a single value like

  • Linux
  • Darwin
  • Windows
  • WINNT

With that info at hand, we can write a function that delivers a boolean result (courtesy of the PHP manual):

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

This takes the output of PHP_OS and looks at the first three characters turned into upper case. If those are identical to WIN it’s Windows – and if not we assume it’s a Linux flavour.

If you need a more detailed information about your environment consider using php_uname():

echo php_uname();

This will give you the above, plus server name, kernel version, release and local server time.



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.