← Back to Chapters

PHP $_GET, $_POST, $_REQUEST Variables

? PHP $_GET, $_POST, $_REQUEST Variables

? Quick Overview

The $_GET, $_POST, and $_REQUEST variables are PHP superglobals used to collect user input from forms and URLs. They allow data to be passed between web pages efficiently.

⚙️ Key Concepts

  • $_GET – Retrieves data from URL query strings.
  • $_POST – Retrieves data sent via HTTP POST requests.
  • $_REQUEST – Retrieves data from both GET and POST methods.

? Syntax & Theory

These superglobals are associative arrays automatically available in all PHP scripts. They do not require initialization.

? Code Example: Using $_GET

? View Code Example
// Accessing data sent through the URL query string
<?php
echo "Name: " . $_GET['name'];
echo "Age: " . $_GET['age'];
?>

? Explanation

Values are passed in the URL like ?name=John&age=25 and accessed using array keys.

? Code Example: Using $_POST

? View Code Example
// Collecting form data using POST method
<form method="POST">
Name: <input type="text" name="name">
Age: <input type="text" name="age">
<input type="submit">
</form>

<?php
echo $_POST['name'];
echo $_POST['age'];
?>

? Explanation

Form values are securely sent in the request body and accessed via $_POST.

? Code Example: Using $_REQUEST

? View Code Example
// Accessing data from either GET or POST
<?php
echo $_REQUEST['name'];
?>

? Explanation

$_REQUEST works with both GET and POST data but should be used cautiously.

? Interactive Example

Below is a simple HTML form that demonstrates how POST data is collected.

This simulates how form data is sent to PHP using POST.

? Use Cases

  • Search filters using URL parameters
  • Login and registration forms
  • Handling multi-page form submissions

✅ Tips & Best Practices

  • Always validate and sanitize user input.
  • Prefer $_POST for sensitive data.
  • Avoid overusing $_REQUEST in secure applications.

? Try It Yourself

  • Create a POST-based contact form and display user input.
  • Pass values via URL using GET and read them in PHP.
  • Experiment with sanitizing inputs using PHP filters.