Posted by CANbike on Fri, 28 Mar 2014

PHP: Detect Linux or Windows Server

PHP is often run on a Linux system or Windows system. If the final hosting server is unknown, or development is on both systems, customization may be required in the script due to operating system differences.

The following provides two simple solutions for detecting the operating system that PHP is running on.


The PHP_OS Constant

PHP_OS is a core predefined constant. It contains the name of the operating system PHP was built on.

Detecting Windows

For increased portability, it may be enough to detect for windows. Possible Windows OS values are:

  • WIN32
  • WINNT
  • Windows

Detecting “WIN” can be done by the PHP conditional statement:

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
{
    echo 'This server currently running PHP is using Windows!';
    define("INCLUDE_DIR","c:\include");
}
else
{
    echo 'This server currently running PHP is not using Windows!';
    define("INCLUDE_DIR", "/include");
}


The php_uname() Function

The php_uname function makes a library call to uname for information about the operating system that PHP is currenlty running on. If the information is unavailable, it will display the OS PHP was built on.

To return the operating system name, specify the ‘s’ mode.

php_uname('s')

and the conditional test for windows is

if (strtoupper(substr(php_uname('s'), 0, 3)) === 'WIN')


php_uname() or PHP_OS

  • Use the constant PHP_OS if only the name of the operating system is required.
  • Use the function php_uname if specific details are required about the operating system PHP is running on.

PHP-Detect Linux or Windows Server-01-thumb.pngPHP-Detect Linux or Windows Server-02-thumb.png


Related Item(s):