PHP ยท Chapter 24 of 44

PHP GET & POST Forms

HTML forms send data to the server using either the GET or POST method. GET appends form data to the URL as a query string, making it visible and bookmarkable, while POST sends data in the request body, keeping it hidden from the URL.

PHP reads GET data through the $_GET superglobal and POST data through $_POST. Choosing between them depends on whether the data is sensitive and whether you want it to appear in the URL.

Syntax
<form method="post" action="submit.php">
  <input type="text" name="username">
</form>

Handling GET requests

GET is suitable for non-sensitive data like search queries or filters, since the data appears in the URL and can be bookmarked or shared.

Handling POST requests

POST is preferred for sensitive data (like passwords) or when submitting large amounts of data, such as file uploads, since it does not expose data in the URL.

Example 1 (php)
<?php
  // submit.php, form used method="post"
  $username = $_POST["username"];
  echo "Hello, $username!";
?>
Output
Hello, Amy!

The value entered in the form's username field is read from $_POST.

Example 2 (php)
<?php
  // URL: search.php?q=php
  $query = $_GET["q"];
  echo "You searched for: $query";
?>
Output
You searched for: php

$_GET reads the q parameter directly from the URL's query string.

Key points

  • GET sends data visibly through the URL; POST sends it in the request body.
  • $_GET and $_POST are used to read the respective form data in PHP.
  • GET is best for non-sensitive, bookmarkable requests.
  • POST is best for sensitive data and larger payloads.
๐Ÿ’ก Note: Never rely on GET for passwords or sensitive information, since URLs can be logged, cached, or shared accidentally.

๐Ÿ“ Quick Quiz

1. Which superglobal reads data from a POST form?

2. Where does GET method data appear?

3. Which method is better suited for submitting passwords?