Disclaimer: This tutorial is designed for beginners to introduce the basics of PHP form handling and sessions. The GET method is used here for demonstration purposes to simplify the learning process. For real-world applications, use the POST method for submitting sensitive data to ensure better security and privacy.
If you're new to PHP and want to learn how to handle forms and work with session data, this guide is for you. We'll build a simple project where a user can submit a form, save the data in a session, view it, and delete it later. By the end of this tutorial, you'll understand the basics of PHP form handling, validation, sanitization, and sessions.
What is Form Handling in PHP?
Form handling refers to the process of capturing data submitted through an HTML form and processing it in a server-side language like PHP. This includes:
-
Fetching the form data: Using methods like
GET
orPOST
. - Validating the data: Ensuring the input meets specific criteria.
- Sanitizing the data: Cleaning the input to prevent security issues like XSS attacks.
- Storing or processing the data: Saving it in sessions, databases, or displaying it back to the user.
What Are Sessions in PHP?
Sessions are a way to store information (variables) across multiple pages for a single user. Unlike cookies, session data is stored on the server, making it more secure. To start using sessions in PHP, we use the session_start()
function.
The Project: PHP Form with Session Handling
Our project involves the following features:
- A user fills out a form with personal information.
- The submitted data is validated and sanitized.
- Valid data is stored in a session.
- Users can view or delete the session data.
File Structure
Here's the structure of our project:
project-folder/
│
├── index.php # Form page
├── submit.php # Form handling and session storage
├── view_session.php # Viewing session data
├── delete_session.php # Deleting session data
Step 1: Creating the Form (index.php
)
The index.php
file contains a simple HTML form where users can input their details. Here's the code:
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Form with Session Handling</title>
</head>
<body>
<h1>Submit Your Information</h1>
<!-- Form Section for User Input -->
<form method="get" action="submit.php">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br><br>
<label for="age">Age:</label><br>
<input type="number" id="age" name="age"><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br><br>
<label for="website">Website:</label><br>
<input type="url" id="website" name="website"><br><br>
<label>Gender:</label><br>
<input type="radio" id="male" name="gender" value="Male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label><br><br>
<label>Hobbies:</label><br>
<input type="checkbox" id="reading" name="hobbies[]" value="Reading">
<label for="reading">Reading</label><br>
<input type="checkbox" id="traveling" name="hobbies[]" value="Traveling">
<label for="traveling">Traveling</label><br>
<input type="checkbox" id="sports" name="hobbies[]" value="Sports">
<label for="sports">Sports</label><br>
<input type="checkbox" id="music" name="hobbies[]" value="Music">
<label for="music">Music</label><br><br>
<label for="comments">Comments:</label><br>
<textarea id="comments" name="comments" rows="4" cols="50" placeholder="Write your comments here..."></textarea><br><br>
<input type="submit" value="Submit">
</form>
<br><br>
<!-- Buttons for View and Delete Session -->
<form action="view_session.php">
<input type="submit" value="View Session Data">
</form>
<form action="delete_session.php">
<input type="submit" value="Delete Session Data">
</form>
</body>
</html>
Step 2: Handling Form Submission (submit.php
)
This file processes the submitted form data, validates it, and stores it in a session. Here's the code:
<?php
session_start();
// Initialize error messages and data variables
$error_name = "";
$error_age = "";
$error_email = "";
$error_website = "";
$name = $age = $email = $website = $gender = $comments = $hobbies = "";
// Sanitize and validate the form data
if ($_SERVER["REQUEST_METHOD"] == "GET") {
// Sanitize inputs
$name = htmlspecialchars(trim($_GET['name']));
$age = htmlspecialchars(trim($_GET['age']));
$email = htmlspecialchars(trim($_GET['email']));
$website = htmlspecialchars(trim($_GET['website']));
$gender = isset($_GET['gender']) ? $_GET['gender'] : 'No gender selected.';
$hobbies = isset($_GET['hobbies']) ? $_GET['hobbies'] : ['No hobby selected.'];
$comments = htmlspecialchars(trim($_GET['comments']));
// Validation checks
if (empty($name)) {
$error_name = "Name is required.";
}
if (empty($age) || !filter_var($age, FILTER_VALIDATE_INT) || $age <= 0) {
$error_age = "Valid age is required.";
}
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_email = "Valid email is required.";
}
if (empty($website) || !filter_var($website, FILTER_VALIDATE_URL)) {
$error_website = "Valid website URL is required.";
}
// If no errors, store data in session
if (empty($error_name) && empty($error_age) && empty($error_email) && empty($error_website)) {
// Store data in session
$_SESSION['name'] = $name;
$_SESSION['age'] = $age;
$_SESSION['email'] = $email;
$_SESSION['website'] = $website;
$_SESSION['gender'] = $gender;
$_SESSION['hobbies'] = implode(", ", $hobbies);
$_SESSION['comments'] = $comments;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Submission Result</title>
</head>
<body>
<h1>Form Submission Result</h1>
<!-- Show Errors if any -->
<?php
if ($error_name) {
echo "<p style='color: red;'>$error_name</p>";
}
if ($error_age) {
echo "<p style='color: red;'>$error_age</p>";
}
if ($error_email) {
echo "<p style='color: red;'>$error_email</p>";
}
if ($error_website) {
echo "<p style='color: red;'>$error_website</p>";
}
if (empty($error_name) && empty($error_age) && empty($error_email) && empty($error_website)) {
// Display the form submission results
echo "<h2>Form Submission Results:</h2>";
echo "<p><strong>Name:</strong> $name</p>";
echo "<p><strong>Age:</strong> $age</p>";
echo "<p><strong>Email:</strong> $email</p>";
echo "<p><strong>Website:</strong> <a href='$website' target='_blank'>$website</a></p>";
echo "<p><strong>Gender:</strong> $gender</p>";
echo "<p><strong>Hobbies:</strong> " . implode(", ", $hobbies) . "</p>";
echo "<p><strong>Comments:</strong> $comments</p>";
}
?>
<br><br>
<a href="index.php">Go Back</a>
</body>
</html>
Step 3: Viewing Session Data (view_session.php
)
This file displays session data stored on the server.
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>View Session Data</title>
</head>
<body>
<h1>View Stored Session Data</h1>
<?php
if (isset($_SESSION['name'])) {
echo "<p><strong>Name:</strong> " . $_SESSION['name'] . "</p>";
echo "<p><strong>Age:</strong> " . $_SESSION['age'] . "</p>";
echo "<p><strong>Email:</strong> " . $_SESSION['email'] . "</p>";
echo "<p><strong>Website:</strong> <a href='" . $_SESSION['website'] . "' target='_blank'>" . $_SESSION['website'] . "</a></p>";
echo "<p><strong>Gender:</strong> " . $_SESSION['gender'] . "</p>";
echo "<p><strong>Hobbies:</strong> " . $_SESSION['hobbies'] . "</p>";
echo "<p><strong>Comments:</strong> " . $_SESSION['comments'] . "</p>";
} else {
echo "<p>No session data found!</p>";
}
?>
<br><br>
<a href="index.php">Go Back</a>
</body>
</html>
Step 4: Deleting Session Data (delete_session.php
)
This file destroys the session data.
<?php
session_start();
session_unset(); // Remove all session variables
session_destroy(); // Destroy the session
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Session Deleted</title>
</head>
<body>
<h1>Session Data Deleted</h1>
<p>All session data has been deleted successfully.</p>
<br><br>
<a href="index.php">Go Back</a>
</body>
</html>
Key Concepts Covered
-
Form Handling:
- Fetching data using the
GET
method. - Validating inputs with conditions and filters.
- Sanitizing inputs with
htmlspecialchars()
.
- Fetching data using the
-
Sessions:
- Starting a session with
session_start()
. - Storing data in
- Starting a session with
the $_SESSION
array.
- Viewing session data.
- Deleting session data using
session_unset()
andsession_destroy()
.
Conclusion
This project demonstrates the basics of PHP form handling and session management. With these concepts, you can build more complex applications that handle user input securely and efficiently. Experiment with the code, and try extending it by adding features like database integration or more advanced validation.
Happy coding! 🚀
Top comments (2)
You should not submit a form of this type using GET. This "article" is in general not a good tutorial on PHP SESSION, just delete it.
This post is intentionally designed for beginners to grasp the fundamentals of PHP forms and session handling, not to mimic real-world scenarios or adhere to advanced practices. The goal is to introduce the concepts in a straightforward way, ensuring that newcomers aren’t overwhelmed. More complex and secure methods come with experience and context, which this foundational understanding aims to prepare them for.