PHP $_REQUEST and $_SERVER


What Are Superglobals?

Superglobals represent built-in PHP arrays which provide global accessibility throughout the entire script without requiring global keyword declaration.

 


What is $_REQUEST?

$_REQUEST merges the data from $_GET, $_POST, and $_COOKIE into one associative array.

 

  • $_GET
  • $_POST
  • $_COOKIE

You can utilize this method to acquire form data through any submission method.

 


Example

<form action="request_example.php" method="POST">
  Name: <input type="text" name="username">
  <input type="submit" value="Submit">
</form> 

<?php
$name = $_REQUEST['username'];
echo "Welcome, $name!";
?> 

notepad

$_REQUEST collects cookie data making it both less secure and less specific

Choose $_POST or $_GET instead for better security and clearer data handling


What is $_SERVER?

The $_SERVER superglobal array holds data about the server environment and the script together with header information.

 


$_SERVER Variables

Variable Name Description
$_SERVER['PHP_SELF'] Returns the filename of the current script
$_SERVER['SERVER_NAME'] Name of the host server
$_SERVER['HTTP_HOST'] Host header (e.g., localhost)
$_SERVER['REQUEST_METHOD'] Request method used (GET/POST)
$_SERVER['SCRIPT_NAME'] Path of the current script
$_SERVER['QUERY_STRING'] The query string of the URL
$_SERVER['REMOTE_ADDR'] IP address of the client
$_SERVER['HTTP_USER_AGENT'] Info about the user’s browser

Example

<?php
echo "Script Name: " . $_SERVER['SCRIPT_NAME'] . "<br>";
echo "Server Name: " . $_SERVER['SERVER_NAME'] . "<br>";
echo "Host: " . $_SERVER['HTTP_HOST'] . "<br>";
echo "Request Method: " . $_SERVER['REQUEST_METHOD'] . "<br>";
echo "Client IP: " . $_SERVER['REMOTE_ADDR'] . "<br>";
echo "Browser Info: " . $_SERVER['HTTP_USER_AGENT'];
?> 

Best Way

  • The $_REQUEST superglobal should be used when the request method is unknown or during rapid prototyping.
  • The $_SERVER superglobal array serves as an essential tool for logging processes and routing mechanisms as well as environment detection and debugging tasks.



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.