I am trying to write code for a guestbook on my website that takes the input from a input text field and a textarea, writes the information to a .txt file and then displays the contents of the .txt file on the screen. This is the code I have so far (I did not write it all)
PHP function to write to text file:

<?php
	// Check if the form is being submitted 
	if ($_POST['usrname'] && $_POST['comments']) 
	{
	$safe_name = strip_tags($_POST['usrname']);
	$safe_comments = strip_tags($_POST['comments']); 

	$record = $safe_name
		."<br />\n-- "
		.$safe_comments
        ."<hr />\n\n";

	$messages = file_get_contents("guestbook.txt");

	// Open the file and clear it out for writing
   
	$loghandle = fopen("guestbook.txt", 'w');
        
	fwrite($loghandle, $record);
	fwrite ($loghandle, $messages);
                
	// Write back in all of the old messages 
	fclose($loghandle);
	}
	else {
		echo "Please fill in the form";
	} ?>

And the HTML/PHP to take the input and display the content:

<div id="middle"><h2 class="headings">The Guest Book<br/><br/><hr/></h2>
	<p class="welcome">Welcome to the guest book page. Fill out the form below and submit it to be added to the guest log for the page. Thanks for visiting!</p>
	<form action="guests.php" method="post">
	<p class="text">Name: <input class="name" name="usrname" type="text"/></p>
	<p class="text">Comments: <textarea name="comments" rows='6' cols='60'></textarea></p>
	<input class="button" type="submit" value="Submit"/>
	</form>
	<?php include("guestbook.txt"); ?>
</div>

The first php statements are outside of the html tags in my code at the top of the file and the second bit of code is inside the body tags. It looks like the function is not even writing the data to the .txt file, which may be why it does not display anything but I saw the php work in the instance it was used prior to this one, I just can't get it to work with my code.

I fixed this issue. It was a problem in the permissions for the .txt file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.