In this tutorial, you’ll learn about the PHP $_REQUEST
superglobal, which is used to collect data sent to the script via both GET and POST methods. This makes it a versatile option for handling user input in web applications.
PHP Superglobal $_REQUEST
1. What is the $_REQUEST Superglobal?
The $_REQUEST
superglobal is an associative array that contains data from the $_GET
, $_POST
, and $_COOKIE
superglobals. It allows you to access user input regardless of the method used to send the data.
2. How $_REQUEST Works
When a user submits data from a form, PHP populates the $_REQUEST
superglobal with that data. It combines input from various sources, making it easier to handle user submissions.
However, it's important to note that using $_REQUEST
can lead to security vulnerabilities, as it can contain data from cookies, which may not be expected. Therefore, it's recommended to use $_GET
and $_POST
explicitly when possible.
3. Accessing Request Data
To access data from the $_REQUEST
superglobal, you can simply use the keys corresponding to the input fields in your HTML form. Here's an example:
<?php
// Assuming a form submission with input field name "username"
$username = $_REQUEST['username'];
echo "Username: " . htmlspecialchars($username);
?>
In this example, the value of the input field named username
is accessed from the $_REQUEST
superglobal.
4. Example: Using $_REQUEST with a Form
Here’s a complete example that demonstrates how to use $_REQUEST
with a simple form:
<form action="" method="POST">
<label for="username">Username:</label>
<input type="text" name="username" id="username" required>
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_REQUEST['username'];
echo "Hello, " . htmlspecialchars($username) . "!";
}
?>
This form collects a username and displays a greeting upon submission.
5. Handling Multiple Inputs
You can also handle multiple input fields using the $_REQUEST
superglobal:
<form action="" method="POST">
<label for="first_name">First Name:</label>
<input type="text" name="first_name" id="first_name" required>
<label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="last_name" required>
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$firstName = $_REQUEST['first_name'];
$lastName = $_REQUEST['last_name'];
echo "Welcome, " . htmlspecialchars($firstName) . " " . htmlspecialchars($lastName) . "!";
}
?>
This example collects both first and last names and displays a welcome message.
6. Conclusion
The $_REQUEST
superglobal is a convenient way to access data submitted by users through forms. However, it's essential to validate and sanitize the input to ensure security and data integrity.
For better control over data handling, consider using $_GET
and $_POST
directly based on the context of your application.