start learning
Image 1

Superglobal $_REQUEST in PHP

In PHP, $_REQUEST is a superglobal variable that provides a combined view of data received from both GET and POST requests. It's an associative array that allows you to access data submitted through forms, query strings, and other request methods. $_REQUEST is often used to handle user input without needing to distinguish between GET and POST methods explicitly.


Example with Clarification :

Here's an example that demonstrates how to use the $_REQUEST superglobal to access data from both GET and POST requests, simplifying the process of handling user input.

<?php
    if (isset($_REQUEST['submit'])) {
        $name = $_REQUEST['name'];
        $email = $_REQUEST['email'];

        echo "<p>Hello, $name! Your email is: $email</p>";
    }
    ?>
<!DOCTYPE html>
<html>
<head>
    <title>PHP $_REQUEST Superglobal Example</title>
</head>
<body>
    <h1>User Information</h1>
    <form method="post" action="">
        <label for="name">Name:</label>
        <input type="text" name="name" id="name">
        <br>
        <label for="email">Email:</label>
        <input type="email" name="email" id="email">
        <br>
        <input type="submit" name="submit" value="Submit">
    </form>
</body>
</html>

  1. In this example, we create a simple HTML form with fields for the user to enter their name and email. The form uses the POST method, which means the data will be sent to the server in the request body.
  2. We use the $_REQUEST superglobal to check if the form was submitted. If the "submit" button is clicked, it indicates a form submission, and we proceed to process the data.
  3. We access the "name" and "email" fields using $_REQUEST['name'] and $_REQUEST['email']. This works for both POST and GET requests, making it convenient for handling user input without worrying about the request method.
  4. We then display a personalized message using the submitted data.

By using $_REQUEST, you can simplify the handling of user input when you don't need to differentiate between GET and POST requests explicitly. It's important to note that while $_REQUEST can be convenient, you should be cautious when using it, as it can introduce security risks if user input is not properly validated and sanitized.