What is the difference between GET and POST method in PHP?
GET and POST are two HTTP methods that a browser uses to send data to the server. PHP reads them with $_GET and $_POST.
| GET | POST | |
|---|---|---|
| Where is the data | In the URL, after the question mark | In the body of the request |
| Visible in the URL | Yes | No |
| Data length | Limited by the URL length (browsers allow about 2000 characters) | Large, limited by post_max_size |
| Bookmark and share | Possible | Not possible |
| Cached by the browser | Yes | No |
| Use for | Reading and searching data: search, filters, page numbers | Sending data that changes something: login, registration, files |
| Safe to repeat | Yes | No, the browser asks before sending again |
GET example. The data is in the URL, like index.php?name=Robin&age=25.
<?php
// URL: index.php?name=Robin&age=25
$name = $_GET["name"] ?? "Guest";
$age = $_GET["age"] ?? "unknown";
echo $name . " is " . $age;
?>
Output:
For the URL above
Robin is 25
POST example. The values are not in the URL.
<form method="post" action="login.php">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">Login</button>
</form>
<?php
// login.php
$username = $_POST["username"] ?? "";
echo "Hello " . htmlspecialchars($username);
?>
Note:
POST is not secret by itself. The data is still visible to anyone who can see the network. Use HTTPS, and never send passwords with GET, because URLs are saved in the browser history and in server logs. Validate all data in both cases, see PHP Forms Handling and PHP Security Tips.
Learn more about the similar topics:
| Tutorials |
|---|
| PHP Forms Handling |
| PHP Send Mail |
| PHP header() Function |
| PHP mail() Function |
| Exercises & Assignments |
|---|
| Create a PHP Form with 2 fields Name and Hobbies |