PHP Superglobal - $_REQUEST (With Examples)

By Shahnail Khan Last updated : December 14, 2023

PHP $_REQUEST

$_REQUEST is a PHP superglobal variable that collects data from various sources, such as HTML forms and URLs. It is an associative array that merges data from $_GET, $_POST, and $_COOKIE arrays. This makes it a versatile tool for handling user input, allowing developers to create dynamic and interactive web applications.

Syntax of PHP $_REQUEST

The syntax to access data from $_REQUEST is:

$value = $_REQUEST['key'];

In the above syntax:

  • $_REQUEST: Refers to the superglobal array that combines data from $_GET, $_POST, and $_COOKIE.
  • 'key': Represents the name of the input field or parameter from which you want to retrieve the value.

Example of PHP $_REQUEST

This examples demonstrates the use of PHP $_REQUEST Superglobal:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  <body>
    <h2>Fill the details:</h2>
    <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
      <input type="text" name="name" placeholder="Enter your name" id="name" required >
      <br>
      <input type="number" name="age" placeholder="Enter your age" >
      <br>
      <button type="submit">Submit</button>
    </form>
    <?php if ($_SERVER["REQUEST_METHOD"] === "POST") {
      // Using $_REQUEST to retrieve the submitted name
      $submittedName = $_REQUEST["name"];

      // Display a greeting message with the submitted name
      echo "<h1><i> Hello, $submittedName! Welcome to IncludeHelp.</i></h1>";
      } ?>
  </body>
</html>

Output

This will appear before giving any input (here, name and age).

superglobal request example output 1

We have created one form in HTML. The form's action is set to <?php echo $_SERVER['PHP_SELF']; ?>, which means it will submit to the same PHP script.

Once you have filled in all the necessary details, you will get the output something like this:

superglobal request example output 2

The PHP code within the HTML handles the form submission. It checks if the request method is "POST" and uses $_REQUEST['name'] to retrieve the submitted name, then displays a greeting message.

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.