Understanding PHP Superglobals: The $_REQUEST Variable

PHP Superglobals: $_REQUEST

Introduction

In PHP, superglobals are built-in variables that are always accessible, regardless of scope. One of the most commonly used superglobals is $_REQUEST, which is particularly useful for handling form data.

What is $_REQUEST?

  • $_REQUEST is an associative array that contains data from:
    • $_GET: Data sent via URL parameters (query strings)
    • $_POST: Data sent via form submission using the POST method
    • $_COOKIE: Data sent through cookies

Key Concepts

  • Data Retrieval: $_REQUEST allows you to retrieve information sent to the server from HTML forms or URLs.
  • Flexibility: It combines data from multiple sources, making it easier to access without worrying about the method used for data submission.

How to Use $_REQUEST

To use $_REQUEST, you simply reference it like any other array in PHP. Here’s how you can access the data.

Example

<!-- Sample form (HTML) -->
<form method="post" action="process.php">
    Name: <input type="text" name="name">
    Age: <input type="text" name="age">
    <input type="submit" value="Submit">
</form>

In process.php, you can access the form data using:

<?php
// Accessing data from $_REQUEST
$name = $_REQUEST['name'];
$age = $_REQUEST['age'];

echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Age: " . htmlspecialchars($age);
?>

Output

If the user submits the form with the name "John" and age "25", the output will be:

Name: John
Age: 25

Important Notes

  • Security: Always sanitize user input to prevent security vulnerabilities like XSS (Cross-Site Scripting) or SQL Injection. Use functions like htmlspecialchars() to escape output.
  • Overriding: Be cautious, as $_REQUEST may contain overlapping data from $_GET, $_POST, and $_COOKIE, leading to potential conflicts.

Conclusion

$_REQUEST is a versatile superglobal in PHP that simplifies data handling from different sources. It’s particularly useful for beginners who want to quickly access form data without worrying about the specific method used. Always remember to sanitize inputs for security purposes!