Google News
logo
PHP Program to $_SERVER - Holds information about headers, paths, and script locations
In the following example of PHP program that demonstrates how to use the `$_SERVER` superglobal variable to access information about headers, paths, and script locations :
Program :
<?php

// Print the server name
echo "Server name: " . $_SERVER["SERVER_NAME"] . "<br>";

// Print the server address
echo "Server address: " . $_SERVER["SERVER_ADDR"] . "<br>";

// Print the request method
echo "Request method: " . $_SERVER["REQUEST_METHOD"] . "<br>";

// Print the request time
echo "Request time: " . date("Y-m-d H:i:s", $_SERVER["REQUEST_TIME"]) . "<br>";

// Print the request URI
echo "Request URI: " . $_SERVER["REQUEST_URI"] . "<br>";

// Print the script name
echo "Script name: " . $_SERVER["SCRIPT_NAME"] . "<br>";

// Print the script filename
echo "Script filename: " . $_SERVER["SCRIPT_FILENAME"] . "<br>";

// Print the document root
echo "Document root: " . $_SERVER["DOCUMENT_ROOT"] . "<br>";

?>
Output :
Server name: localhost
Server address: ::1
Request method: GET
Request time: 2023-05-01 00:00:00
Request URI: /test.php
Script name: /test.php
Script filename: /var/www/html/test.php
Document root: /var/www/html
In this example, we have used various elements of the `$_SERVER` superglobal array to output information about the server and the current request. Some of the most commonly used `$_SERVER` variables include :

* `$_SERVER["SERVER_NAME"]`: the server name

* `$_SERVER["SERVER_ADDR"]`: the server IP address

* `$_SERVER["REQUEST_METHOD"]`: the HTTP request method (e.g. GET or POST)

* `$_SERVER["REQUEST_TIME"]`: the Unix timestamp of the start of the request

* `$_SERVER["REQUEST_URI"]`: the requested URI (Uniform Resource Identifier)

* `$_SERVER["SCRIPT_NAME"]`: the name of the current script

* `$_SERVER["SCRIPT_FILENAME"]`: the absolute path of the current script

* `$_SERVER["DOCUMENT_ROOT"]`: the document root directory for the current request


Note that some of the `$_SERVER` variables may not be available on all systems, and their values may depend on the web server and PHP configuration. It's always a good idea to check the PHP documentation and test your code on different systems to ensure compatibility and reliability.