views:

56

answers:

1

Title says it all. I need to determine the type of OS the PHP server is running on. By type, I mean strings like "windows" or "linux", not "wince", "winnt" etc.

So far, I have to leads: PHP_OS and uname(), the later being more reliable than the earlier (PHP_OS says what OS PHP was built on - according to documentation).

+1  A: 

It's important to know that no non-Windows OS string is going to contain the text "win", and no non-OSX OS string is going to contain the word "darwin", and so on. Detecting the OS is easy.

$uname = strtolower(php_uname());
if (strpos($uname, "win") !== false) {
    // It's windows
} else if (strpos($uname, "darwin") !== false) {
    // It's OSX
} else if (strpos($uname, "linux") !== false) {
    // It's Linux
} else {
    // It's something your script won't run on
}
mellowsoon
It detects OSX as windows ;-). I've got this code already, but as I said, it ain't reliable.
Christian Sciberras
Now I'm not calling you a liar or crazy, but that sounds impossible! haha
mellowsoon
P.S. Note the order of the if than statements. It will grab the "win" in "darwin" if you're checking for OSX first.
mellowsoon
Oh and by the way, do you know the above conditionals for other OSes (hpux, xenix, haiku...)?
Christian Sciberras
With regards to your PS, that is exactly why I replied so above. It will see "win" in "darwin" and think it is "windows".
Christian Sciberras
Have the code search for `darwin` first!
webbiedave
"With regards to your PS, that is exactly why I replied so above. It will see "win" in "darwin" and think it is "windows"." Er, no. This is why you first check for windows. If the first if/then statement is satisfied, the rest are ignored. If will only check the "darwin" string if the windows string failed.
mellowsoon
As far as other OS's.. There's no point in checking for OS's that PHP can't even be installed on.
mellowsoon
Pseudocode 1: "windows" contains "win"? Yes, therefore it is windows. Pseudocode 2: "darwin" contains "win"? Yes, therefore it is windows.
Christian Sciberras
the correct order would be: check for "darwin", check for "win", check for "linux"...
slosd
slosd is right. You DO need to check for Darwin first. My bad ;)
mellowsoon
Tehehe. Just edit the code and we'll try to forget it ever happened :P
Christian Sciberras
ahah Well now that you wrote that I can't! Maybe next time. ;)
mellowsoon