Home Backend Development PHP Tutorial Beginner&#s Guide to PHP Form Handling with Sessions

Beginner&#s Guide to PHP Form Handling with Sessions

Dec 04, 2024 pm 09:11 PM

Beginner

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:

  1. Fetching the form data: Using methods like GET or POST.
  2. Validating the data: Ensuring the input meets specific criteria.
  3. Sanitizing the data: Cleaning the input to prevent security issues like XSS attacks.
  4. 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
Copy after login

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">




<hr>

<h3>
  
  
  Step 2: Handling Form Submission (submit.php)
</h3>

<p>This file processes the submitted form data, validates it, and stores it in a session. Here's the code:<br>
</p>

<pre class="brush:php;toolbar:false"><?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>




<hr>

<h3>
  
  
  Step 3: Viewing Session Data (view_session.php)
</h3>

<p>This file displays session data stored on the server.<br>
</p>

<pre class="brush:php;toolbar:false"><?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>
Copy after login

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>
Copy after login

Key Concepts Covered

  1. Form Handling:

    • Fetching data using the GET method.
    • Validating inputs with conditions and filters.
    • Sanitizing inputs with htmlspecialchars().
  2. Sessions:

    • Starting a session with session_start().
    • Storing data in

the $_SESSION array.

  • Viewing session data.
  • Deleting session data using session_unset() and session_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! ?

The above is the detailed content of Beginner&#s Guide to PHP Form Handling with Sessions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles