How to make a guest book php
Learn how to create a guestbook in PHP, with a step-by-step example!
Creating a Guest Book with PHP
Creating a guest book with PHP is a relatively straightforward process. To get started, you'll need to create the HTML form that will be used to capture user input. Start by creating a file called guestbook.html and save it in the same directory as your PHP script.
<form action="guestbook.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<label for="comment">Comment:</label>
<textarea name="comment" id="comment"></textarea>
<input type="submit" value="Submit">
</form>
The HTML form above has two fields, one for the user's name and one for their comment. The form is configured to send a POST request to the guestbook.php script when the form is submitted.
Next, you'll need to create the guestbook.php script that will handle the form submission. Start by creating a file called guestbook.php in the same directory as your HTML form.
<?php
// get the data from the form
$name = $_POST['name'];
$comment = $_POST['comment'];
// format the comment for storage
$comment = htmlspecialchars($comment);
$comment = nl2br($comment);
// open the guestbook file
$guestbook = fopen("guestbook.txt", "a");
// write the data to the file
fwrite($guestbook, $name . " - " . $comment . "n");
// close the file
fclose($guestbook);
?>
The guestbook.php script above retrieves the name and comment data from the form using the $_POST array. It then formats the comment for storage by converting any HTML characters to their respective entities, and then converting newlines to line breaks. Finally, it opens the guestbook.txt file for writing, writes the data to the file, and closes the file.
Now that the form and script are in place, you can view the guestbook.html page in your browser, enter some data, and submit the form. The data will be written to the guestbook.txt file, which you can open and view to confirm that everything is working properly.
Creating a guest book with PHP is a relatively straightforward process. With just a few lines of code, you can have a functional guest book up and running in no time.