In PHP, the $_GET, $_POST, and $_REQUEST superglobals are used to collect form data. While they all serve similar purposes, each has its unique characteristics and use cases. Let’s dive into each one!
🔹 What is $_GET?
The $_GET method is used to send data via the URL. This method is typically used for non-sensitive information, like search queries or page navigation, since the data is visible in the URL.
📝 Example 1: Using $_GET to Collect Data
This form submits data using the GET method:
<form action="process.php" method="get">
Name: <input type="text" name="username"> <br>
<input type="submit" value="Submit">
</form>
In the PHP file, retrieve the submitted data using $_GET:
<?php
if (isset($_GET['username'])) {
$username = $_GET['username'];
echo "Hello, $username!";
} else {
echo "Please enter your name.";
}
?>
🔹 What is $_POST?
The $_POST method is used to send data via an HTTP POST request. Unlike $_GET, the data is not visible in the URL, making it a better choice for sensitive information like passwords.
📝 Example 2: Using $_POST to Collect Data
This form submits data using the POST method:
<form action="process.php" method="post">
Name: <input type="text" name="username"> <br>
<input type="submit" value="Submit">
</form>
In the PHP file, retrieve the submitted data using $_POST:
<?php
if (isset($_POST['username'])) {
$username = $_POST['username'];
echo "Hello, $username!";
} else {
echo "Please enter your name.";
}
?>
🔹 What is $_REQUEST?
The $_REQUEST method is a combined superglobal that retrieves data from both $_GET and $_POST methods, as well as $_COOKIE data. It’s useful when you’re unsure which method will be used for submission, but it may pose security risks as it includes data from multiple sources.
📝 Example 3: Using $_REQUEST to Collect Data
This form works with both GET and POST methods, and you can access the submitted data using $_REQUEST:
<form action="process.php" method="post">
Name: <input type="text" name="username"> <br>
<input type="submit" value="Submit">
</form>
In the PHP file, retrieve the submitted data using $_REQUEST:
<?php
if (isset($_REQUEST['username'])) {
$username = $_REQUEST['username'];
echo "Hello, $username!";
} else {
echo "Please enter your name.";
}
?>
🔹 Key Differences Between $_GET, $_POST, and $_REQUEST
$_GET– Sends data via the URL, visible to everyone. Best for non-sensitive information like search queries.$_POST– Sends data in the body of the request. More secure for sensitive data like passwords or personal information.$_REQUEST– Retrieves data from$_GET,$_POST, and$_COOKIE. Use cautiously as it can introduce security risks.
📝 Practice Time!
Modify the form to send data with both GET and POST methods. Retrieve the data using $_GET, $_POST, and $_REQUEST to compare their behavior!