PHP $_REQUEST

In PHP, the $_REQUEST superglobal is used to collect form data from both $_GET and $_POST methods. It provides a simple way to access input values without worrying about the request type.

🔹 How Does $_REQUEST Work?

The $_REQUEST array holds data sent via HTTP GET, POST, and COOKIE methods. It is useful when you are unsure which method will be used to submit the form.

📝 Example 1: Simple Form Using $_REQUEST

This form allows users to submit their name. Whether they use GET or POST, the value will be retrieved using $_REQUEST.

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

Now, let’s process the submitted data:

<?php
if (isset($_REQUEST['username'])) {
    $name = $_REQUEST['username'];
    echo "Hello, $name!";
} else {
    echo "Please enter your name.";
}
?>

Try It Now


🔹 $_REQUEST vs. $_GET vs. $_POST

Although $_REQUEST is convenient, it is not always the best choice. Let’s compare:

  • $_GET – Retrieves data sent via the URL (useful for search queries).
  • $_POST – Retrieves data sent via an HTTP POST request (secure for form submissions).
  • $_REQUEST – Retrieves data from both GET and POST, but may also include COOKIE data, making it less secure.

🔹 Handling Missing or Empty $_REQUEST Values

Always check if the form fields are set before using them.

<?php
$name = isset($_REQUEST['username']) ? $_REQUEST['username'] : "Guest";
echo "Welcome, $name!";
?>

Try It Now

Output: If no username is provided, it defaults to “Guest”.


🔹 Why Should You Be Careful with $_REQUEST?

Since $_REQUEST includes $_GET, $_POST, and $_COOKIE, there is a risk of unintended data overriding. For security reasons, it is often better to use $_POST or $_GET explicitly.


🎯 Key Takeaways

  • $_REQUEST collects form data from both GET and POST requests.
  • It is convenient but can lead to security risks if misused.
  • For secure data handling, prefer $_POST over $_REQUEST.

📝 Practice Time!

Modify the form to include an email field and process it using $_REQUEST. Try submitting data with both GET and POST methods!