Help with Comment Box using php

Can someone help me make my Comment Box code work. I want it to use the php file to auto-email the comment and then I can post the comment myself.

HTML CODE:

<head>
	<meta charset="UTF-8">
  	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="style.css">
</head>

      	 <div class="comment-box">
           <br>
		<h2>Comments</h2>
		<form method="post" action="send_mail.php">
		<label>Name
		<input type="text" name="name" placeholder="Name not required...">
		</label>
            	<br>
            	<label>Comment
		<textarea name="comment" maxlength="650" placeholder="Type your comment here..." required></textarea>
            	</label>
        	<br>
    		<button type="submit">Submit Comment</button>
		<br>
	</form>
	</div>

        <br>
        <br>
        Comments go here.
        <br>
        <br>

CSS StyleSheet:

* {
	padding: 8;
	margin: 0;
}
.comment-box {
	top: 50%;
	left: 50%;
	width: 500px;
}
.comment-box h2 {
	font-size: 20px;
	margin-bottom: 15px;
}
.comment-box input {
	width: 100%
	height: 50px;
	padding: 8 20px;
	margin-bottom: 15px;
	border-radius: 5px;
	border: 1px solid #86b0b6;
}
.comment-box input:focus {
	border: 1px solid #000;
	outline: 0;
}
.comment-box textarea {
	width: 100%;
	height: 150px;
	padding: 15px 20px;
	margin-bottom: 10px;
	border-radius: 5px;
	border: 1px solid #86b0b6;
} 
.comment-box textarea:focus {
	border: 1px solid #000;
	outline: 0;
}
.comment-box button {
	border:0;
	padding: 10px 30px;
	background: #86b0b6;
	font-size: 18px;
	border-radius: 5px;
	color: #fff;
}

PHP e-mail form:

<?php
/*
This first bit sets the email address that you want the form to be submitted to.
You will need to change this value to a valid email address that you can access.
*/
$webmaster_email = "MY_PRIVATE_EMAIL@hotmail.com";

/*
This bit sets the URLs of the supporting pages.
If you change the names of any of the pages, you will need to change the values here.
*/
$feedback_page = "antarctica.html";
$error_page = "messages/error_message.html";
$thankyou_page = "messages/thank_you.html";

/*
This next bit loads the form field data into variables.
If you add a form field, you will need to add it here.
*/
$comment = $_REQUEST['comment'] ;
$name = $_REQUEST['name'] ;
$msg = 
"Name: " . $name . "\r\n" . 
"Comment: " . $comment ;

/*
The following function checks for email injection.
Specifically, it checks for carriage returns - typically used by spammers to inject a CC list.
*/
function isInjected($str) {
	$injections = array('(\n+)',
	'(\r+)',
	'(\t+)',
	'(%0A+)',
	'(%0D+)',
	'(%08+)',
	'(%09+)'
	);
	$inject = join('|', $injections);
	$inject = "/$inject/i";
	if(preg_match($inject,$str)) {
		return true;
	}
	else {
		return false;
	}
}


// If the form fields are empty, redirect to the error page.
elseif empty($comment)) {
header( "Location: $error_page" );
}

/* 
If email injection is detected, redirect to the error page.
If you add a form field, you should add it here.
*/
elseif isInjected($name)  || isInjected($comment) ) {
header( "Location: $error_page" );
}

// If we passed all previous tests, send the email then redirect to the thank you page.
else {

	mail( "$webmaster_email", "Feedback Form Results", $msg );

	header( "Location: $thankyou_page" );
}
?>

So what part of it isnt working?

I uploaded the files to:

and here is the error I get:

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

okay so the PHP has a problem in it somewhere. Lets see.

Well, I can see a couple immediate problems.

elseif isInjected($name) || isInjected($comment) ) {
Count your parenthesis, and fill in the missing one.
elseif empty($comment)) {
same, but should be easier to see in this line…

elseif empty($comment)) {
(Yes, the same line) What is this an elseif… to? There’s no if for this to elseif off of.

1 Like

Thanks for the advice! I think I made those changes properly. I got the php code from somewhere, I don’t remember.

Can someone rewrite me something that would work, even if it doesn’t do the email injection. As long as it sends an email so I can add the comment myself, that would be awesome. At this point I doubt I will ever figure out how to store data and make my own comment system without adding each comment making it look like I just approve them like that haha

K well, thanks for your help!

<?php
/*
This first bit sets the email address that you want the form to be submitted to.
You will need to change this value to a valid email address that you can access.
*/
$webmaster_email = "chrisdugan5@hotmail.com";

/*
This bit sets the URLs of the supporting pages.
If you change the names of any of the pages, you will need to change the values here.
*/
$feedback_page = "antarctica.html";
$error_page = "messages/error_message.html";
$thankyou_page = "messages/thank_you.html";

/*
This next bit loads the form field data into variables.
If you add a form field, you will need to add it here.
*/
$comment = $_REQUEST['comment'] ;
$name = $_REQUEST['name'] ;
$msg = 
"Name: " . $name . "\r\n" . 
"Comment: " . $comment ;

/*
The following function checks for email injection.
Specifically, it checks for carriage returns - typically used by spammers to inject a CC list.
*/
function isInjected($str) {
	$injections = array('(\n+)',
	'(\r+)',
	'(\t+)',
	'(%0A+)',
	'(%0D+)',
	'(%08+)',
	'(%09+)'
	);
	$inject = join('|', $injections);
	$inject = "/$inject/i";
	if(preg_match($inject,$str)) {
		return true;
	}
	else {
		return false;
	}
}


// If the form fields are empty, redirect to the error page.
if empty($comment) {
header( "Location: $error_page" );
}

/* 
If email injection is detected, redirect to the error page.
If you add a form field, you should add it here.
*/
elseif isInjected($name)  || isInjected($comment) {
header( "Location: $error_page" );
}

// If we passed all previous tests, send the email then redirect to the thank you page.
else {

	mail( "$webmaster_email", "Feedback Form Results", $msg );

	header( "Location: $thankyou_page" );
}
?>

No, the forum isn’t really a custom code-writing service. Plenty of people are happy to help you figure out why the code you write isn’t working properly / doing what you want it to, but it’s unlikely someone will take time out and write your code for you.

1 Like

@chrisdugan1 when you post code on the forum, you need to format it. That’s what the </> button is for…

okay, I understand that. :slight_smile:
anyway, here is what I shortened the code to make it as simple as possible and it still doesn’t work:`

<?php
$webmaster_email = "chrisdugan5@hotmail.com";
$feedback_page = "antarctica2.htm";
$thankyou_page = "messages/thank_you.html";
$name = $_REQUEST['name'] ;
$comment = $_REQUEST['comment'] ;
$msg = "Name: " . $name . "Comment: " . $comment;
	mail( "$webmaster_email", "Comment on Antarctica-UFO.com", $msg );
	header( "Location: $thankyou_page" );
?>

You should enable error reporting for PHP. This will give you more specific pointer to errors within the code.
On the live site they should be logged. But ideally you should have a local development environment where the errors may be displayed.

This can be done using a database, but maybe take it one step at a time at this stage.

What does that mean, exactly? How far through does it get? Is your development system configured to send mail?

So if you do not quote the webmaster variable and add a proper FROM header that would look more correct to me.

$headers = "From: ". $webmaster_email . "\r\n";
mail($webmaster_email, "Comment on Antarctica-UFO.com", $msg, $headers);

However the FROM email really should be a domain email address like info@dug.name so look into setting up a email with your host and use it for sending emails From your domain.

Thanks! I am currently moving my website to a different hosting company. I am going to wait until that is all set up. I will be back as soon as I can.
Thanks again everyone!!

You should probably look into using phpmailer to send your emails. It should have examples in the download… See this SitePoint article. https://www.sitepoint.com/sending-emails-php-phpmailer/

Your mail section would then be more like this.

	use PHPMailer\PHPMailer\PHPMailer;
	use PHPMailer\PHPMailer\Exception;
	
	require_once "vendor/autoload.php";
	
	//PHPMailer Object
	$mail = new PHPMailer(true); //Argument true in constructor enables exceptions
	
	//From email address and name
	$mail->From = "from@yourdomain.com";
	//$mail->FromName = "Full Name";
	
	//To address	
	//$mail->addAddress("recepient1@example.com", "Recepient Name");
	$mail->addAddress($webmaster_email); //Recipient name is optional
	
	//Send HTML or Plain Text email
	$mail->isHTML(false);
	
	$mail->Subject = "Feedback Form Results";
	$mail->Body = $msg;
	$mail->AltBody = $msg;
	
	try {
		$mail->send();
		header("Location: ".$thankyou_page);
		exit;
	} catch (Exception $e) {
		echo "Mailer Error: " . $mail->ErrorInfo;
	}
3 Likes

Thank you all for your help!
I got my files over to the new server, enabled php and got it working in no time at all :smiley:

<?php
$webmaster_email = "anonymised@anonymised.com";
$thankyou_page = "thank_you.html";
$name = $_REQUEST['name'] ;
if (empty($name)) {
	 $name='Anonymous (Named By ME)';
}
$comment = $_REQUEST['comment'] ;
$msg = "Name: " . $name . "\r\nComment: " . $comment;
	mail( "$webmaster_email", "Comment on Antarctica-UFO.com", $msg );
	header( "Location: $thankyou_page" );
?>

Before I go ahead and try to make a database, would it even be possible to allow replies to comments and place them under the original comment? If so, do you think this would be a hard task?

Yes, it would be possible - how do you think forums and places like Facebook do it. No, it doesn’t need to be all that difficult.

Every comment will have a unique ID, and can optionally have a second ID to indicate which comment it is replying to. Use the presence of the second one to decide whether it’s an original comment, or a reply, though of course you can have replies to replies and you need to decide how far down you want that to go.

thanks for that!
anyway, did you try my contact form? I made it so you need 10 characters for the comment but someone managed to send a message with only 1 character, “1” and the name “1”
well, that is strange and I wonder how, when I can’t do it without 10 characters lol

Without seeing the code, it’s impossible for anyone to guess why that might be happening.

No, I didn’t. I thought you said it was all working so I didn’t feel there was any need to.

How did you enforce this?

Edit:-

I have a good guess, but want to OP to answer first, it may be an important lesson.

personally, I am unable to submit the form without at least 10 characters in the comment text box.
(using required + minlength=“10”)
Code:

    			<form method="post" action="send_mail.php">
            		<label>Name
    				<input type="text" name="name" placeholder="Name not required..." maxlength="40">
        			</label>
            		<br>
            		<label>Comment
    				<textarea name="comment" minlength="10" maxlength="650" placeholder="Type your comment here.... (to reply to a comment, include details like name & date)" required oninvalid="this.setCustomValidity('Please type a comment.')" oninput="setCustomValidity('')"></textarea>
            		</label>
        			<br>
    				<button type="submit">Submit Comment</button>
					<br>
    			</form>

Thanks again for the help!

And here is the answer and the important lesson.
Anything on the client side can be edited by anyone to whatever they like, the HTML, the CSS, the Javascript. It’s easily done in the Dev Tools of any common browser.
This causes some serious security concerns. So any validation you do on the client side, must be backed up by validation on the server side.
Never trust anything coming form the client side!
For something simple like minimum length:-

if(strlen(trim($_POST['comment'])) < $minlen) { $errors[] = "The comment must be at least $minlen characters." ;}

Of course this idea of your code being tampered with on the client side poses more serious threats than a short comment, but you are learning.

Edit
Just adding this screen recording to show how eaily someone can tamper with your form data. You could literally change anything, the value of pre-set inputs, the input names, any validation attributes.
Mozilla Firefox 2023-05-17 18-03-20
You can even write a whole new form that submits to your action URL.