About Lesson
Handling GET and POST data
In PHP, we often get input from users through HTML forms. When a form is submitted, the data goes to the server using either the GET or POST method. PHP has superglobals $_GET and $_POST to access this data.
1. GET Method:
- Sends form data in the URL.
- Data is visible in the browser’s address bar.
- It is not secure; it is useful for search forms, filters, or when you need to bookmark.
- Data limit: up to 2000 characters approximately.
Example:
HTML
<!-- HTML Form (get.html) -->
<form method="get" action="process_get.php">
Name: <input type="text" name="username">
Age: <input type="number" name="age">
<input type="submit" value="Submit">
</form>
PHP
<?php
// process_get.php
$name = $_GET['username'];
$age = $_GET['age'];
echo "Your Name: " . $name . "<br>";
echo "Your Age: " . $age;
?>
Explanation:
- If input is
Name = John
,Age = 25
- URL will look like: http://localhost/process_get.php?username=John&age=25
- Output:
- Your Name: John
- Your Age: 25
2. POST Method:
- Sends form data in the request body, not in the URL.
- It is more secure than GET because it does not display passwords or personal details.
- There is no size limit, making it better for large data and file uploads.
Example:
PHP
<!-- HTML Form (post.html) -->
<form method="post" action="process_post.php">
Email: <input type="email" name="email">
Password: <input type="password" name="password">
<input type="submit" value="Login">
</form>
HTML
<?php
// process_post.php
$email = $_POST['email'];
$password = $_POST['password'];
echo "Your Email: " . $email . "<br>";
echo "Your Password: " . $password;
?>
Explanation:
- If input is
Email = abc@gmail.com
,Password = 12345
- URL will remain clean: http://localhost/process_post.php
- Output:
- Your Email: abc@gmail.com
- Your Password: 12345
Difference between GET and POST:
Feature | GET | POST |
---|---|---|
Data Location | Appended in URL | Sent in request body |
Security | Less secure (visible) | More secure (hidden) |
Data Limit | Around 2000 characters | No limit (depends on server) |
Use Cases | Search, filters, bookmarks | Login forms, file upload, sensitive data |