search
HomeBackend DevelopmentPHP TutorialBeginner&#s Guide to PHP Form Handling with Cookies

Beginner

In this guide, we'll explore PHP form handling using cookies to store user data. Cookies are a way to persist small amounts of data on the user's browser, making it possible to remember user preferences or information across different sessions.

Our project involves creating a form where users can input their information, storing the submitted data in cookies, and then viewing or deleting the cookie data. By the end of this tutorial, you'll understand how to set, retrieve, and delete cookies in PHP.


What Are Cookies?

Cookies are small files stored on the user's browser. They allow web servers to store data specific to a user and retrieve it on subsequent visits. In PHP, you can work with cookies using the setcookie() function to create or update cookies and the $_COOKIE superglobal to read them.


The Project: PHP Form with Cookie Handling

We'll create a simple application that:

  1. Allows users to submit their information via a form.
  2. Stores the submitted data in cookies.
  3. Displays the stored cookie data.
  4. Provides an option to delete the cookies.

File Structure

Our project includes the following files:

project-folder/
│
├── index.php           # Form page
├── submit.php          # Form handling and cookie storage
├── view_cookie.php     # Viewing cookie data
├── delete_cookie.php   # Deleting cookie data

Step 1: Creating the Form (index.php)

The index.php file contains the HTML form for user input, along with buttons to view or delete cookie data.



    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP Form with Cookie Handling</title>


    <h1 id="Submit-Your-Information">Submit Your Information</h1>
    <!-- Form Section for User Input -->
    


Step 2: Handling Form Submission (submit.php)

The submit.php file processes the form data, validates and sanitizes it, and then stores it in cookies.

<?php // 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'] : '';
    $hobbies = isset($_GET['hobbies']) ? $_GET['hobbies'] : [];
    $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, set cookies
    if (empty($error_name) && empty($error_age) && empty($error_email) && empty($error_website)) {
        // Set cookies for the form data
        setcookie("name", $name, time() + (86400 * 30), "/");
        setcookie("age", $age, time() + (86400 * 30), "/");
        setcookie("email", $email, time() + (86400 * 30), "/");
        setcookie("website", $website, time() + (86400 * 30), "/");
        setcookie("gender", $gender, time() + (86400 * 30), "/");
        setcookie("hobbies", implode(", ", $hobbies), time() + (86400 * 30), "/");
        setcookie("comments", $comments, time() + (86400 * 30), "/");
    }
}
?>




    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Submission Result</title>


    <h1 id="Form-Submission-Result">Form Submission Result</h1>

    <!-- Show Errors if any -->
    <?php if ($error_name) {
        echo "<p>




<hr>

<h3>
  
  
  Step 3: Viewing Cookie Data (view_cookie.php)
</h3>

<p>This file displays the cookie data stored on the user's browser.<br>
</p>

<pre class="brush:php;toolbar:false">


    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Cookie Data</title>


    <h1 id="View-Stored-Cookie-Data">View Stored Cookie Data</h1>

    <?php if (isset($_COOKIE['name'])) {
        echo "<p><strong>Name:</strong> " . $_COOKIE['name'] . "";
        echo "<p><strong>Age:</strong> " . $_COOKIE['age'] . "</p>";
        echo "<p><strong>Email:</strong> " . $_COOKIE['email'] . "</p>";
        echo "<p><strong>Website:</strong> <a href="%22%20.%20%24_COOKIE%5B" website . target="_blank">" . $_COOKIE['website'] . "</a></p>";
        echo "<p><strong>Gender:</strong> " . $_COOKIE['gender'] . "</p>";
        echo "<p><strong>Hobbies:</strong> " . $_COOKIE['hobbies'] . "</p>";
        echo "<p><strong>Comments:</strong> " . $_COOKIE['comments'] . "</p>";
    } else {
        echo "<p>No cookie data found!</p>";
    }
    ?>

    <br><br>
    <a href="index.php">Go Back</a>



Step 4: Deleting Cookie Data (delete_cookie.php)

This file deletes the cookies by setting their expiration time to the past.

<?php // Deleting cookies by setting their expiration time to past
setcookie("name", "", time() - 3600, "/");
setcookie("age", "", time() - 3600, "/");
setcookie("email", "", time() - 3600, "/");
setcookie("website", "", time() - 3600, "/");
setcookie("gender", "", time() - 3600, "/");
setcookie("hobbies", "", time() - 3600, "/");
setcookie("comments", "", time() - 3600, "/");
?>




    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cookie Deleted</title>


    <h1 id="Cookies-Deleted">Cookies Deleted</h1>
    <p>All cookies have been deleted successfully.</p>
    <br><br>
    <a href="index.php">Go Back</a>



Conclusion

This project demonstrates how to use cookies for form handling in PHP. By implementing cookies, you can persist user data and improve the functionality of your web applications. Experiment with this project and explore more advanced use cases for cookies in PHP.

Happy coding! ?

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

Statement
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
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

HTTP Method Verification in LaravelHTTP Method Verification in LaravelMar 05, 2025 pm 04:14 PM

Laravel simplifies HTTP verb handling in incoming requests, streamlining diverse operation management within your applications. The method() and isMethod() methods efficiently identify and validate request types. This feature is crucial for building

Discover File Downloads in Laravel with Storage::downloadDiscover File Downloads in Laravel with Storage::downloadMar 06, 2025 am 02:22 AM

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software