Handling form with GET
& POST
PHP provides two methods through which a client (browser)
can send information to the server. These methods are given below, and
discussed in detail:
1. GET
method.
2. POST
method.
Get and Post methods are the HTTP request methods used
inside the <form> tag to send form data to the server.
HTTP protocol enables the communication between the client
and the server where a browser can be the client, and an application running on
a computer system that hosts your website can be the server.
GET method:-
The GET method is used to submit the HTML form data. This
data is collected by the predefined $_GET variable for processing.
The information sent from an HTML form using the GET method
is visible to everyone in the browser's address bar, which means that all the
variable names and their values will be displayed in the URL. Therefore, the
get method is not secured to send sensitive information.
For Example: localhost/gettest.php?username=sumit&password=bca
Characteristics:
·
Form data is sent as part of the URL.
·
Data is visible in the browser's address bar.
·
Useful for actions like searching where data
doesn't need to be secure.
·
Limited by the URL length.
·
Most modern browsers support a URL length of up
to 2000–2048 characters.
<!-- HTML Form -->
<form method="GET" action="process_form.php">
<label for="name">Name:</label>
<input type="text" name="name">
<button type="submit">Submit</button>
</form>
<?php
// process_form.php
if (isset($_GET['name'])) {
$name = htmlspecialchars($_GET['name']); // Sanitize input to prevent
XSS
echo "Hello,
" . $name;
}
?>
<html>
<body>
<form action="welcome.php"
method="GET">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
Advantages of GET method (method = "get")
·
You can bookmark the page with the specific
query string because the data sent by the GET method is displayed in URL.
·
GET requests can be cached.
·
GET requests are always remained in the browser
history.
Disadvantages of GET Method
·
The GET method should not be used while sending
any sensitive information.
·
A limited amount of data can be sent using
method = "get". This limit should not exceed 2048 characters.
·
For security reasons, never use the GET method
to send highly sensitive information like username and password, because it
shows them in the URL.
·
The GET method cannot be used to send binary
data (such as images or word documents) to the server.
post method:-
Unlike the GET method, it does not have a limit on the
amount of information to be sent. The information sent from an HTML form using
the POST method is not visible to anyone.
For Example: localhost/posttest.php
Note that the "post" method is more secure than
the "get" method because the data sent using the POST method is not
visible to user.
The POST method in PHP is used to send form data securely to
the server in the request body, without appending it to the URL. It is ideal
for sensitive or larger data submissions, such as login forms or uploading
files.
HTML Form
Create an HTML form that uses the POST method:
<form method="POST" action="process_post.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
PHP Script to Process POST Data
Handle the submitted form data in a PHP file:
<?php
// Check if the request is
POST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//
Retrieve and sanitize user inputs
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
//
Display the data (for demonstration purposes)
echo "Name:
" . $name . "<br>";
echo "Email:
" . $email;
} else {
echo "Invalid
request.";
//header ("Location: one.php");
}
?>
Advantages of POST method (method = "post")
·
The POST method is useful for sending any
sensitive information because the information sent using the POST method is not
visible to anyone.
·
There is no limitation on size of data to be
sent using the POST Method. You can send a large amount of information using
this method.
·
Binary and ASCII data can also be sent using the
POST method.
·
Data security depends on the HTTP protocol
because the information sent using the POST method goes through the HTTP
header. By using secure HTTP, you can ensure that your data is safe.
Disadvantages of POST Method
POST requests do not cache.
POST requests never remain in the
browser history.
It is not possible to bookmark the
page because the variables are not displayed in URL.
Example 2 :
upload_form.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>File Upload Example</title>
</head>
<body>
<h1>Upload a File</h1>
<form action="upload_file.php" method="POST" enctype="multipart/form-data">
<label for="file">Choose a file:</label>
<input type="file" name="file" id="file" required>
<button type="submit">Upload</button>
</form>
</body>
</html>
upload_file.php:
<?php
// Check if a file has been
uploaded
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
$uploadedFile = $_FILES['file'];
//
Extract file details
$fileName = $uploadedFile['name'];
$fileTmpPath = $uploadedFile['tmp_name'];
$fileSize = $uploadedFile['size'];
$fileError = $uploadedFile['error'];
$fileType = $uploadedFile['type'];
//
Define the target directory
$targetDirectory = "uploads/";
//
Ensure the upload directory exists
if (!is_dir($targetDirectory)) {
mkdir($targetDirectory, 0777, true); //
Create the directory if it doesn't exist
}
//
Define the full path for the uploaded file
$targetFilePath = $targetDirectory . basename($fileName);
// Check
for upload errors
if ($fileError === UPLOAD_ERR_OK) {
// Move
the uploaded file to the target directory
if (move_uploaded_file($fileTmpPath, $targetFilePath)) {
echo "File
uploaded successfully!<br>";
echo "File
name: " . htmlspecialchars($fileName) . "<br>";
echo "File
size: " . ($fileSize / 1024) . " KB<br>";
echo "File
type: " . htmlspecialchars($fileType) . "<br>";
echo "Stored
at: " . htmlspecialchars($targetFilePath);
} else {
echo "Error:
Failed to move the uploaded file.";
}
} else {
echo "Error:
An error occurred during file upload.";
}
} else {
echo "Error:
No file uploaded.";
}
?>
The enctype="multipart/form-data" attribute in an
HTML <form> element specifies how the form data should be encoded when it
is sent to the server.
Why It’s Necessary
·
When uploading files using an HTML <form>,
the browser needs to:
·
Handle text fields separately from file data.
·
Send the file data in binary format.
·
Include metadata about the file (like file name
and type).
·
This is accomplished with the
multipart/form-data encoding.