PHP $_SERVER: Usage Guide & Examples

In PHP, $_SERVER is an array that contains various server variables. It holds information related to the current script’s runtime environment, such as request headers, paths, file locations, and more.

Variables in the $_SERVER array are set by the server and can be used anywhere. Here are some commonly used $_SERVER variables and their functions:

  1. $_SERVER[‘PHP_SELF’]: The filename of the currently executing script.
  2. The $_SERVER[‘SERVER_NAME’] represents the host name of the server that is currently running the script.
  3. $_SERVER[‘HTTP_HOST’]: The hostname from the current request header.
  4. $_SERVER[‘REQUEST_METHOD’]: The HTTP method of the current request.
  5. $_SERVER[‘REQUEST_URI’]: The URI of the current request (including the query string).
  6. $_SERVER[‘QUERY_STRING’]: The portion of the current request that contains the query string.
  7. $_SERVER[‘HTTP_REFERER’]: The URL of the previous page that requested the current page.
  8. $_SERVER[‘HTTP_USER_AGENT’]: Information about the current request’s user agent (browser).

In addition to the variables mentioned above, there are many other $_SERVER variables that can be used to retrieve information related to the server environment. You can check all available variables and their values by printing the $_SERVER array.

print_r($_SERVER);

Note: $_SERVER is a superglobal variable, so it can be accessed anywhere in the script without the need for the global keyword.

bannerAds