Programming Languages
PHP
Subjective
Nov 23, 2012
Differentiate GET and POST methods?
Detailed Explanation
GET and POST are HTTP methods for sending data between client and server.
Detailed Comparison:
| Feature | GET | POST |
|---|---|---|
| Data Location | URL query string | Request body |
| Data Limit | ~2048 characters | No practical limit |
| Security | Less secure (visible) | More secure (hidden) |
| Caching | Can be cached | Not cached |
| Bookmarking | Can be bookmarked | Cannot be bookmarked |
| Idempotent | Yes | No |
GET Method Examples:
// URL: https://example.com/search.php?q=php&category=tutorial
// Accessing GET data
$searchQuery = $_GET["q"] ?? "";
$category = $_GET["category"] ?? "all";
// Validate and sanitize
$searchQuery = filter_var($searchQuery, FILTER_SANITIZE_STRING);
if (strlen($searchQuery) > 100) {
$searchQuery = substr($searchQuery, 0, 100);
}
// Build search results
$results = searchDatabase($searchQuery, $category);
POST Method Examples:
// HTML Form
<form method="POST" action="process.php">
<input type="text" name="username" required>
<input type="password" name="password" required>
<input type="submit" value="Login">
</form>
// Processing POST data
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING);
$password = $_POST["password"];
// Validate
if (empty($username) || empty($password)) {
$error = "All fields are required";
} else {
// Process login
$user = authenticateUser($username, $password);
}
}
When to Use:
- GET: Search, filtering, pagination, public data retrieval
- POST: Login, registration, file uploads, data modification
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts