GET and POST Methods in PHP
Overview
PHP provides two methods through which a client (browser) can send information to the server:
- GET method
- POST method
These methods are HTTP request methods used inside the <form>
tag to send form data to the server. HTTP protocol enables communication between the client (browser) and the server (application hosting the website).
GET Method
The GET method is used to submit the HTML form data, collected by the predefined $_GET
variable for processing. The information sent via GET is visible in the browser's address bar, making it less secure for sensitive data.
Characteristics:
- Data is sent via URL as query strings.
- Limited to 2000 characters (URL length limit).
- Less secure as data is exposed in the URL.
- Suitable for simple data retrieval.
Syntax:
$_GET['key_name'];
Example (using isset()
function):
<!DOCTYPE html>
<html lang="en">
<head>
<title>GET Method Example</title>
</head>
<body>
<form method="GET" action="">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<input type="submit" value="Submit">
</form>
<?php
if (isset($_GET['name'])) {
$name = $_GET['name'];
echo "Hello, " . htmlspecialchars($name);
}
?>
</body>
</html>
POST Method
The POST method sends data to the server securely by including it in the request body, not in the URL.
Characteristics:
- Data is sent as part of the HTTP request body.
- No size limitation on data.
- More secure as data isn't exposed in the URL.
- Suitable for sensitive data like passwords or large data submissions.
Syntax:
$_POST['key_name'];
Example:
<body>
<form method="POST" action="">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['email'])) {
$email = $_POST['email'];
echo "Your email is: " . htmlspecialchars($email);
}
?>
</body>
Example with Separate .HTML and .PHP Files
GET Method
form.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>GET Method Example - Form</title>
</head>
<body>
<h1>GET Method Form</h1>
<form method="GET" action="process.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
process.php:
<!DOCTYPE html>
<html lang="en">
<head>
<title>GET Method Example - Process</title>
</head>
<body>
<h1>Processed Data</h1>
<?php
if (isset($_GET['name']) && isset($_GET['age'])) {
$name = htmlspecialchars($_GET['name']);
$age = htmlspecialchars($_GET['age']);
echo "<p>Name: $name</p>";
echo "<p>Age: $age</p>";
} else {
echo "<p>No data received.</p>";
}
?>
</body>
</html>
Tags:
php