Funnotes Logo
Home Sai Satcharitra Talapatram

Writing a Guestbook in PHP

[BACK]

A Guestbook is an important place in one's website. It acts as a mirror of what others feel and think about a website. So, without wasting any further time, lets jump directly into, 'How To Create it'.

An HTML Form: It is the primary requirement which acts as an interface from where an user can enter details. Although explaining everything about FORMs is out of scope here, I explain it to the extent we needed in creating a guestbook.

A Sample HTML Form: Below is a sample HTML form. This form works on the POST method of transmitting data to the webserver. To see how actual form looks like, Click Here. When the Submit button is clicked, form variables like "guestName, guestEmail, guestUrl, guestCity, guestState, guestCountry and guestComments" (see the HTML code below to see these variables) are transferred to the script TakeGuestIn.php as specified in the code below for Action attribute.

<form method=POST action=TakeGuestIn.php>
<em>Name *: </em> <input type=text name=guestName size=40><br>
<em>E-Mail: </em> <input type=text name=guestEmail size=40><br>
<em>URL: http:// </em> <input type=text name=guestUrl size=50><br>
<em>City: </em> <input type=text name=guestCity size=15>
<em>State: </em> <input type=text name=guestState size=15>
<em>Country: </em> <input type=text name=guestCountry size=15>
<br>
<em>Your Comments:* </em><br>
<textarea name=guestComments COLS=60 ROWS=4></textarea>
<br><em>* Fields are mandatory.</em><br>
<input type=submit value="Sign"> <input type=reset value="Erase All">
<form>

Now the real work is lied with in that TakeGuestIn.php script where we will handle all the variables that we receive and write them in required formats into a file to access later.

Concept: The whole concept of guestbook in a NutShell is,

  • Take the data in from user
  • save the data in a file in required format, preferably in HTML format
  • Access the data later to display it on a website (webpage)

Actual Guestbook Code: Below is the actual PHP code for 'Guestbook' where we deal with the data that is received in the script when the submit button is clicked in the HTML form.

NOTE: Variables (like the Form Fields shown here) can be accessed through SUPER_GLOBALS in PHP. That is any variable submitted to the script can be accessed as $_POST['variableName'] if they are submitted in POST method or as $_GET['variableName'] if they are submitted in GET method. For Example, the form field guestName here can be accessed as $_POST['guestName'].

<?php
	// script written by V Rama Aravind. Copyrights vested with author.
	// no unauthorised copying or distribution of code from this page.
	// wed, 20 july, 2005.
	// script to add guest book entries

	// take in variables and check for mandatory ones
	// if everything is satisfied write them into a file in the required format, (HTML)
	if(empty($_POST['guestName']) || empty($_POST['guestComments']))
	{
		print "<br>>Your <em>Name</em> and <em>Comments</em> BOTH are essential My Friend.
		Please <a href="yourFileName.php">Go Back</a> to enter them, thanks.";
	}
	else	// carry on with handling the form
	{
		$FinalContents="<!--start guest entries-->\n\nGuest's Comments:
		<b>".$_POST['guestComments']."</b><br>"."Guest's Name: <i>".$_POST['guestName'].
		"</i><br>";
		
		if(!empty($_POST['guestEmail']))
		{
			if(strpos($_POST['guestEmail'], "@"))
			{
				$FinalContents=$FinalContents."EMail: <a href=mailto:
				{$_POST['guestEmail']}>{$_POST['guestName']}'s Email ID</a><br>";
			}
		}

		if(!empty($_POST['guestUrl']))
		$FinalContents=$FinalContents."URL: <a href=http://{$_POST['guestUrl']}>Click here
		to go to ".$_POST['guestName']."'s webpage</a><br>";

		if(!empty($_POST['guestCity']))
		$FinalContents=$FinalContents."Location: ".$_POST['guestCity'].", ";

		if(!empty($_POST['guestState']))
		$FinalContents=$FinalContents.$_POST['guestState'].", ";

		if(!empty($_POST['guestCountry']))
		$FinalContents=$FinalContents.$_POST['guestCountry'].". <br>";

		$FinalContents=$FinalContents."Date and Time Signed: ".date("r");

		$FinalContents=$FinalContents."<hr><br>";

		$ultFileContents=file_get_contents("ShowGuestEntries.php");
		$ultFinalContents=str_replace("<!--start guest entries-->", $FinalContents,
		$ultFileContents);

		$showGuestEntryFile=fopen("ShowGuestEntries.php", "w");
		fwrite($showGuestEntryFile, $ultFinalContents);
		fclose($showGuestEntryFile);

		print "<br><em><b class=\"highlight\">Here is what you entered</b></em>
		<em>{$_POST['guestName']}</em><br><br>";
		print $FinalContents;

		// send a short mail to one who signed
		if(!empty($_POST['guestEmail']))
		{
			if(strpos($_POST['guestEmail'], "@"))
			{
				$to=$_POST['guestEmail'];
				$message="Hello {$_POST['guestName']},\n\nThanks for signing
				my guestbook.";
				$message=wordwrap($message, 70);
				$headers='From: you@yourdomain.com';
				mail($to, "{$_POST['guestName']} - thanks for signing my guestbook",
				$message, $headers);
			}
		}
	}
?>
[BACK][TOP]

In this script we are taking each variable like this, $_POST['guestName'] and

  • we are checking whether the variable is set or not using isempty(...) function
  • if either Name or Comments are not entered, we are printing a warning message to ask user to enter details again
  • we are maintaining a variable called $finalContents to hold the final contents that needs to be written to a file and displayed as a feedback
  • we are checking if the variable $_POST['guestEmail'] is a valid email address or not by testing the presence of '@' sign in it.
  • One by one, we are appending the form fields (variables) into the variable $finalContents as a string by checking whether they are empty or not. If any variable is empty then it is discarded. This is achieved through isempty(...) function.
  • and we are appending Date through date(...) function
  • and after that we are decorating the text by adding rulers and break points <hr> and <br>
  • then we are writing the thus formed $finalContents into a file called ShowGuestEntries.php - a tricky part here is explained later
  • and as a last step print the $finalContents varible's contents using the print function and if necessary send an email to the one who signed the guestbook with a Thank you message, by checking that their email ID satisfies minimum requirements for it to be a valid e-mail ID (check for '@' sign)

The code shown above is self-explanatory but it deserves a bit of explanation on how to write the data into the files. One possible approach is,

  • to Open a file in Append mode and append the entries at the end of the file.

But with this approach New entries will be added below the old entries, which is not quite satisfactory. The other good approach that i used here is, place a thumbmark in the file. Like for example <!--start Guest Entries--> that I used here.

Now, when the data is submitted to the script and after all the necessary steps of formatting the data into a single variable as explained before are done and when you are about to the write that data into a file, check for the thumbmark <!--start Guest Entries--> and replace it with the newly formed contents. That's not totally done, you should make that file ready for this script to write another new data also, for that you should take care that the thumbmark <!--start Guest Entries--> is entered into your $finalContents variable before any data is appended to it. The first line in the else block, in the code shown above, shows this.

$FinalCntnts="<!--start guest entries-->\n\nGuest's Comments: <b>".$_POST['guestComments']."</b>...

That's it, these are the steps for creating a guestbook in PHP. One big advantage with using PHP is that it is almost similar to 'C' and is hence easy to follow and write effective code. You can download the actual files from my My Programs page. You can copy and redistribute the files and code, maintained that the original copyright message in the file is not altered.

V Rama Aravind
26-08-2005

© 2003 - 2023, Rama Aravind Vorray, Inc. Site Last Updated: 2023-04-08. Contact Me