How do I use PHP to create a simple guestbook?

Creating a Simple Guestbook with PHP

A guestbook is a valuable addition to any website that wants to encourage user engagement and interaction. In this tutorial, we will learn how to create a simple guestbook using PHP and a text file for storing the messages. By the end of this tutorial, you should be able to create a basic guestbook that allows users to submit their names and messages and displays them on your website.

Step 1: Create the HTML form for user input

First, let’s create an HTML form that allows users to enter their names and messages. This form will send the submitted data to a PHP script for processing.

<!-- html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Guestbook</title>
</head>
<body>
    <h1>Simple Guestbook</h1>
    <form action="guestbook.php" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <br>
        <label for="message">Message:</label>
        <textarea id="message" name="message" rows="4" cols="50" required></textarea>
        <br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Step 2: Create the PHP script to process user input

Now that we have the HTML form set up, let’s create a PHP script called “guestbook.php” to process the submitted data. This script will read the user’s input, save it to a text file, and display the messages.

<?php
# PHP
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the user's input
    $name = htmlspecialchars($_POST["name"]);
    $message = htmlspecialchars($_POST["message"]);

    // Format the input for storage
    $formatted_message = $name . "|||" . $message . PHP_EOL;

    // Save the message to a text file
    file_put_contents("guestbook.txt", $formatted_message, FILE_APPEND);

    // Redirect back to the guestbook page
    header("Location: {$_SERVER['REQUEST_URI']}");
    exit;
}
?>

Step 3: Display the guestbook messages

After processing the user’s input, let’s display the saved messages on the guestbook page. We will read the contents of the text file, parse the messages, and display them as a list.

<?php
# PHP
// Read the messages from the text file
$messages = file("guestbook.txt", FILE_IGNORE_NEW_LINES);

// Display the messages
echo "<h2>Guestbook Entries:</h2>";
echo "<ul>";

foreach ($messages as $msg) {
    list($name, $message) = explode("|||", $msg);
    echo "<li><strong>{$name}:</strong> {$message}</li>";
}

echo "</ul>";
?>

Put it all together:

Now, you can put the PHP code from Step 2 and Step 3 in the same file “guestbook.php”, just above the HTML code from Step 1. This will create a single file that handles both input and display of guestbook messages.

Got question?

Submit it here

© All rights reserved.