How can session variables be effectively used to store and retrieve form data for sending via email in PHP?

To effectively use session variables to store and retrieve form data for sending via email in PHP, you can store the form data in session variables when the form is submitted, and then retrieve the data from the session variables when constructing the email. This ensures that the data is retained across different pages or requests until it is sent via email.

<?php
session_start();

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $_SESSION['name'] = $_POST['name'];
    $_SESSION['email'] = $_POST['email'];
    $_SESSION['message'] = $_POST['message'];
}

// Retrieve form data from session variables
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$message = $_SESSION['message'];

// Construct email
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$body = "Name: $name\nEmail: $email\nMessage: $message";
$headers = "From: $email";

// Send email
mail($to, $subject, $body, $headers);
?>