0
0
PHPprogramming~5 mins

$_REQUEST behavior in PHP

Choose your learning style9 modes available
Introduction

$_REQUEST lets you get data sent by a user through forms or URLs in one simple place.

When you want to get data from a form that can use GET or POST methods.
When you want to read query parameters from a URL or form inputs without checking each method separately.
When you want a quick way to access user input without worrying about where it came from.
When you want to handle both cookies and form data in one place (if configured).
Syntax
PHP
$_REQUEST['key']

$_REQUEST is a PHP superglobal array that contains data from $_GET, $_POST, and $_COOKIE.

The order of data in $_REQUEST depends on the PHP configuration setting request_order or variables_order.

Examples
This code gets the 'name' value from any request method and prints a greeting.
PHP
<?php
// Access a value sent by GET, POST, or COOKIE
$name = $_REQUEST['name'];
echo "Hello, $name!";
?>
This checks if 'age' was sent and prints it or a message if not.
PHP
<?php
// Check if a value exists in $_REQUEST
if (isset($_REQUEST['age'])) {
    echo "Age is " . $_REQUEST['age'];
} else {
    echo "Age not provided.";
}
?>
Sample Program

This program demonstrates that manually assigning values to $_GET, $_POST, and $_COOKIE inside the script does not populate $_REQUEST, as $_REQUEST is assembled from incoming HTTP request data before the script executes. In real scenarios, $_REQUEST prioritizes based on request_order (typically 'GP', so GET then POST).

PHP
<?php
// Simulate GET and POST data
$_GET['color'] = 'blue';
$_POST['color'] = 'red';
$_COOKIE['color'] = 'green';

// By default, request_order is usually 'GP' meaning GET then POST
// But let's print what $_REQUEST['color'] gives

echo "Color from $_REQUEST: " . $_REQUEST['color'] . "\n";

// To show the difference, print each superglobal
echo "Color from $_GET: " . $_GET['color'] . "\n";
echo "Color from $_POST: " . $_POST['color'] . "\n";
echo "Color from $_COOKIE: " . $_COOKIE['color'] . "\n";
?>
OutputSuccess
Important Notes

$_REQUEST can be slower and less secure because it mixes data sources.

It's better to use $_GET, $_POST, or $_COOKIE directly when you know where data should come from.

Check your PHP request_order setting to understand which data $_REQUEST uses first.

Summary

$_REQUEST combines GET, POST, and COOKIE data into one array.

It is easy to use but can cause confusion if you don't know the data source order.

Use it for quick access, but prefer specific superglobals for clarity and security.