Programming - - By Harry Fuecks

PHP Server API Differences

A useful table: Apache and IIS PHP $_SERVER Superglobal Comparision.

If you’ve written code that’s had to run under more than one web server environment (even PHP as CGI vs. PHP as module under Apache), you’ve probably run into headaches like $_SERVER[‘SCRIPT_FILENAME’] being unavailable – Server APIs (SAPIs) vary.

Ran into the link table a few days ago and it illustrates potential problems nicely (I assume that the IIS column was created from PHP running as an ISS “module”, not as a CGI executable). Perhaps the two most critical are $_SERVER[‘SCRIPT_FILENAME’] and $_SERVER[‘REQUEST_URI’], both of which you’re likely to want if you’re doing anything “frameworky” but are are generally only available to PHP running as an Apache module.

The link doesn’t quite raise the full story though. As I remember, with PHP as a CGI under Apache, $_SERVER[‘SCRIPT_FILENAME’] is the path to the CGI executable, not the script it is executing – that relates to a request for a PHP constant called __MAIN__ to identify the script where execution began.

Otherwise the various HTTP_ variables in $_SERVER array could vary per-request – these tell you information about the incoming HTTP request. There’s also the informational X_HTTP_ that sometimes show up, such as X_HTTP_FORWARDED_FOR – a convention amongst proxy servers. None of these you should trust by the way.

There’s further fun to be had with Apache 2 and $_SERVER[‘PATH_TRANSLATED’] – see here. The PHP function php_sapi_name() is useful for determining which environment your scripts are running under. Side note here – believe it returns “apache” when PHP is running as an module under Apache 1.x and 2.x.

And if you were thinking – “Who cares? I’ll just rely on good old $_SERVER[‘PHP_SELF’] right?” then you should read this – searching Google for “form tutorial PHP_SELF” is the stuff of nightmares.

Some work has been done to provide SAPI-specific functionality to help “understand” parts of the environment (e.g. Apache and NSAPI allow you to get more information about incoming requests) but, IMO, the bottom line is there’s a minefield if you’re writing code that should run under more than one SAPI.

Right now don’t have any particular answers or conclusions. PHP is a cross platform technology, not platform independent. The #1 problem, to my mind, is there doesn’t seem to be any definitive documentation of where the differences lie. There’s a bunch of tips attached to the manual on predefined variables but most of these are of the “this worked for me” kind. In a perfect world all of this might be hidden behind an API that magically works it all out, but I’m not aware of anything that offers this.

Thoughts / opinions / links etc.?

Sponsors