Recently I have created guestbook, thought I share my recepie with you, I made it with ChatGPT 3.5 and very little knowledge of JS and PHP.
Enjoy Reading💘


A Simple Guestbook Will Need Html, CSS, JS, and PHP.
You’ll need a simple HTML page with CSS styling and use JavaScript to handle the form submission and save the data to a feedback.json file. Since JavaScript running in a browser cannot write directly to the local file system for security reasons, we’ll use a server-side script to handle the data storage. For this example, we’ll use PHP to write the data to the feedback.json file.

The following code will give user frontend to submit input in website:

<form id="feedbackForm">
 
   <label for="name">Name:</label>
   <input type="text" id="name" required>
 
   <label for="website">Website (optional):</label>
   <input type="url" id="website">
 
   <label for="email">Email:</label>
   <input type="email" id="email" required>
 
   <label for="message">Message:</label>
   <textarea id="message" required></textarea>
 
   <button type="submit">Sign My Guestbook!</button>
 
</form>

Also you need to link js file into html index file.

 <script src="script.js"></script>

This is JavaScript file. It the engine which will make the magick of processing input action happen.

document.getElementById('feedbackForm').addEventListener('submit', function(event) {
    event.preventDefault();
 
    const name = sanitizeInput(document.getElementById('name').value);
    const website = sanitizeInput(document.getElementById('website').value);
    const email = sanitizeInput(document.getElementById('email').value);
    const message = sanitizeInput(document.getElementById('message').value);
    const dateTime = new Date().toLocaleString();
 
    const formData = {
        name,
        website,
        email,
        message,
        dateTime
    };
 
    saveFeedback(formData);
});
 
function sanitizeInput(input) {
    // Implement input sanitization or use a library for this purpose
    // For this example, we'll simply trim leading and trailing spaces
    return input.trim();
}
 
function saveFeedback(data) {
    // Use XMLHttpRequest or fetch() to send data to the server
    // In this example, we'll use fetch() to send a POST request to the PHP script
    fetch('save_feedback.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            alert('Success! You are Great! Thanks for your feedback buddy!');
        } else {
            alert('Damn, Something Not Right! Try Again!');
        }
    })
    .catch(error => {
        alert('Oops, Not Quite Right! Try Again!');
        console.error(error);
    });
}

If you noticed I made sure the script have sufficient security features against input injection and XSS vulnerabilties implemented, You can further add your own protective measures for increased security.

The Following php code will store the user input in JSON file.

<?php
// Validate the incoming JSON data to ensure it's properly formatted
$jsonData = json_decode(file_get_contents('php://input'), true);
 
if (!empty($jsonData)) {
    // Validate individual input fields for potential attacks or injections
    $name = validateInput($jsonData['name']);
    $website = validateInput($jsonData['website']);
    $email = validateInput($jsonData['email']);
    $message = validateInput($jsonData['message']);
    $dateTime = $jsonData['dateTime'];
 
    // Validate email format using PHP filter_var function
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        sendErrorResponse('Invalid email format');
        exit;
    }
 
    // Additional validation for other fields can be added if required
      // Append the data to feedback.json file
    $filename = 'feedback.json';
    $jsonData = json_decode(file_get_contents($filename), true) ?? [];
    $jsonData[] = [
        'name' => $name,
        'website' => $website,
        'email' => $email,
        'message' => $message,
        'dateTime' => $dateTime
    ];
 
    // Write to the file in a secure manner
    if (file_put_contents($filename, json_encode($jsonData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) !== false) {
        sendSuccessResponse();
    } else {
        sendErrorResponse('Failed to save feedback data');
    }
} else {
    sendErrorResponse('Invalid data received');
}
 
 
function validateInput($input) {
    // Implement additional input validation and sanitization here
    // For this example, we'll simply remove leading and trailing spaces
    return trim($input);
}
 
function sendSuccessResponse() {
    // Send a JSON response back to the client (JavaScript)
    header('Content-Type: application/json');
    echo json_encode(['success' => true]);
}
 
function sendErrorResponse($message) {
    // Send a JSON response back to the client (JavaScript) in case of error
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => $message]);
}
?>

Now until this point we have done but if you still insist Lets go two step further and add notification system so you’ll be notified via email whenever someone sign your guestbook.

Create notify.sh script

#!/bin/bash
 
# Read the last entry from feedback.json
last_entry=$(tail -n 8 feedback.json)
 
# Customize the email notification content here
subject="New Guestbook Entry"
recipient="neovoid@envs.net"
 
# Send email using mutt
echo -e "$last_entry" | mutt -s "$subject" -- "$recipient"

You’ll need some mechanism to watch for changes in feedback.json file and triggers the execution of notify.sh

guestbook_Listener.sh

#!/bin/bash
echo feedback.json | entr notify.sh

entr is the unix program that listens for file changes and execute commands when changes occur to file.

Now you can make this guestbook_Listener.sh file run in the background in various way.
One I used here is with systemd user services.

More on that on Seperate blog of its own.

Till Then Happy Coding!