Tuesday, May 15, 2012

PHP script - detect whether running under linux or Windows?


I have a PHP script that may be placed on a windows system or a linux system. I need to run different commands in either case.



how can i detect which environment i am in? (preferably something php rather than clever system hacks)





sorry sorry!! the script is running from the command line!!!!


Source: Tips4all

4 comments:

  1. 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_unameDocs:

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

    ReplyDelete
  2. The php_uname function can be used to detect this.

    echo php_uname();

    ReplyDelete
  3. Core Predefined Constants: http://us3.php.net/manual/en/reserved.constants.php which has the PHP_OS (string) constant.

    Or if you want to detect the OS of the client:

    <?php
    echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

    $browser = get_browser(null, true);
    print_r($browser);
    ?>


    From http://us3.php.net/manual/en/function.get-browser.php



    According to your edit you can refer to this dublicate PHP Server Name from Command Line

    You can use

    string php_uname ([ string $mode = "a" ] )


    So

    php_uname("s")



    's': Operating system name. eg.
    FreeBSD.


    Would do the trick for you, see here http://php.net/manual/en/function.php-uname.php

    ReplyDelete
  4. not the most robust way to do a test, but you can check if the directory seperator is / (linux) or \ windows. the constant name is DIRECTORY_SEPARATOR

    if (DIRECTORY_SEPARATOR == '/') {
    // linux
    }

    if (DIRECTORY_SEPARATOR == '\') {
    // windows
    }

    ReplyDelete