PHP Super Global Variables
There are various predefine “superglobals” in PHP. These variables can easily accessible in function or class. Following are the superglobals variables:
- $GLOBALS
- $_SERVER
- $_REQUEST
- $_POST
- $_GETetc.
<?php $nos1 = 20; $nos2 = 30; function addition() { $GLOBALS['nos'] = $GLOBALS['nos1'] + $GLOBALS['nos2']; } addition(); echo $nos; ?>Output 50 PHP $_SERVER PHP $_SERVER is a PHP super global variable that holds the information about headers, paths, and script locations. Example 2:
<?php echo $_SERVER['PHP_SELF']; echo "<br>"; echo $_SERVER['SERVER_NAME']; echo "<br>"; echo $_SERVER['HTTP_HOST']; echo "<br>"; echo $_SERVER['HTTP_USER_AGENT']; echo "<br>"; echo $_SERVER['SCRIPT_NAME']; ?>Output /crud/hello.php localhost localhost Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36 /crud/hello.php Superglobals variables are given below:
Element/Code | Description |
$_SERVER['PHP_SELF'] | Returns the filename of the currently executing script |
$_SERVER['GATEWAY_INTERFACE'] | Returns the version of the Common Gateway Interface (CGI) the server is using |
_SERVER['SERVER_ADDR'] | Returns the IP address of the host server |
$_SERVER['HTTPS'] | Is the script queried through a secure HTTP protocol |
$_SERVER['SCRIPT_URI'] | Returns the URI of the current page |
<html> <body> <h3>Enter Your Name to Display result</h3> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> <input type="text" name="fname" placeholder="Enter your name..."><br><br> <input type="submit"> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // collect value of input field $name = $_REQUEST['fname']; if (empty($name)) { echo "Name is empty"; } else { echo $name; } } ?> </body> </html>PHP $_POST PHP $_POST is used to collect data after submitting the form using“$_post”method. It is also used to pass the variables. Example
<html> <body> <h3>Enter Your Name to Display result</h3> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> <input type="text" name="fname" placeholder="Enter your name..."><br><br> <input type="submit"> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // collect value of input field $name = $_POST['fname']; if (empty($name)) { echo "Name is empty"; } else { echo $name; } } ?> </body> </html>