GET & POST
HTML forms can be used to send data from one page to another.
PHP can then retrieve the data.
There are two common methods for sending form data:
- GET
- POST
GET
The GET method sends the form data as part of the URL.
<form action="result.php" method="GET">
Name:
<input type="text" name="name">
<input type="submit">
</form>
If the user enters Alex, the URL might become:
- result.php?name=Alex
PHP uses $_GET to retrieve the data:
<?php
$name = $_GET["name"];
echo "<p>Hello $name</p>";
?>
POST
The POST method sends the data without displaying it in the URL.
<form action="result.php" method="POST">
Name:
<input type="text" name="name">
<input type="submit">
</form>
PHP uses $_POST to retrieve the data:
<?php
$name = $_POST["name"];
echo "<p>Hello $name</p>";
?>
GET vs POST
| GET | POST |
|---|---|
| Data appears in the URL | Data does not appear in the URL |
When to Use Each
| GET | POST |
|---|---|
| Used when requesting or retrieving information | Used when sending information to be processed or saved |
| Good for searches and filters | Good for sign-up and login forms |
| Data appears in the URL | Data does not appear in the URL |
| URLs can be bookmarked or shared with the values included | Submitted data is not stored in a shareable URL |
| Should not be used for passwords or sensitive information | Better suited to passwords or sensitive information |