Problem with New Contact Page

I’ve created a new contact page for my website that I’ve struggled with for the past 3 days. I’ve gotten most of the bugs out of it, but one remains that I can’t get my head around. Errors appear as soon as the page opens in the fields they apply to as if it was left blank when the submit button was pressed. If I clear the error messages in each field and fill in the appropriate data, it sends the email. It’s like it’s processing the post php before the HTML. I’d appreciate a fresh set of eyes on my code. Here it is:

<?php
// initialization
session_start();

$email_contact = "[email protected]";
$email_website = "[email protected]";

// definition of permitted types/subject/category. use to dynamically build the option list,
// pre-selecting any existing choice, and used in the validation logic
$permitted_types = ['Questions', 'Report Problem', 'Suggestion', 'Other', 'Website Problem'];

$post = []; // array to hold a trimmed working copy of the form data
$errors = []; // array to hold user/validation errors


// post method form processing
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
	// trim all the data at once
	$post = array_map('trim',$_POST); // if any of the fields are arrays, use a recursive call-back function here instead of php's trim function

	// inputs: name, email, type/subject/category, message - all required
	
	// validate the inputs
	if($post['name'] === '')
	{
		$errors['name'] = 'Name is required.';
	}
	if($post['email'] === '')
	{
		$errors['email'] = 'Email is required.';
	}
	else
	{
		// while it is true that the following email format validation will produce an error
		// for an empty value, you should specifically tell the visitor what is wrong with what
		// they submitted
		if (false === filter_var($post['email'], FILTER_VALIDATE_EMAIL))
		{
			$errors['email'] = 'The Email Address you entered does not appear to be valid.';
		}
	}
	if($post['type'] === '')
	{
		$errors['type'] = 'You must select a Type/Subject/Category.';
	}
	else
	{
		// you will only see the following error due to a programming mistake or someone/something submitting their own values
		if(!in_array($post['type'],$permitted_types))
		{
			$errors['type'] = 'The selected Type is invalid.';
			// you would want to log the occurrence of this here...
		}
	}
	if($post['message'] === '')
	{
		$errors['message'] = 'Message is required.';
	}
	else
	{
		if(strlen($post['message']) < 10)
		{
			$errors['message'] = 'The Message must be at least 10 characters.';
		}
	}

	// if no errors, use the submitted data
	if(empty($errors))
	{

		// apply htmlentities() to help prevent cross site scripting when viewing the received email in a browser
		$formcontent = htmlentities("From: {$post['name']}\r\nEmail: {$post['email']}\r\nSubject: {$post['type']}\r\nMessage: {$post['message']}", ENT_QUOTES);

		if ($post['type'] === "Website Problem")
		{
			$recipient=$email_website;
		}
		else
		{
			$recipient=$email_contact;
		}

		// add $post['email'] as a Reply-to: header if desired, it is one, valid email address at this point
		$mailheader = "From: $email\r\n";

		if(!mail($recipient, $post['type'], $formcontent, $mailheader))
		{
			// an error
			// setup the user error message
			$errors['mail'] = 'The email could not be sent, the site owner has been notified.';
		
			// system error handling goes here... - datatime, get the last error message, include the mail parameter values...
			// at this point, all parameters are either an internal value, have been validated they they are just an expected 
			// value/format, or have had htmlentities() applied.
			
		}
	
		// if no errors at this point, success
		if(empty($errors))
		{
			$_SESSION['success_message'] = "Mail Sent. Thank you {$post['name']}, we will contact you shortly..";
			die(header("Refresh:0"));
		}
	}
}

// html document starts here...
?>


<?php
// display any success message
if(!empty($_SESSION['success_message']))
{
	// for demo purposes, just output it as a paragraph. add any markup/styling you want
	echo '<p>';
	echo htmlentities($_SESSION['success_message'], ENT_QUOTES);
	echo " - <a href='index.php#home' style='color:#ff0099;'> Return Home</a>";
	echo '</p>';
	unset($_SESSION['success_message']);
}
?>

<?php
// display any errors
if(!empty($errors))
{
	// for demo purposes, just output them as a paragraph. add any markup/styling you want
	echo '<p>'; echo implode('<br>',$errors); echo '</p>';
}
?>

<?php
// (re)display the form here..., re-populating the fields with any existing values


?>

<?php require_once("header.php");?>

<style>
  input, select {
  width: 20rem;
  line-height:30px;
  border:2px solid #2f496e;
  padding: 0;
  margin: 0;
  height: 30px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  font: 500 1rem sans-serif;
  background: #fff;
}

.input {
  text-indent: 3px;
}
</style>

</head>
<body>
  <?PHP require_once("navbar.php"); ?>
<!--******************
*      CONTACT       *     
*******************-->

<div class="head__h1"> Need help? Have a suggestion? Why not send us an email?</div>     
  <div class="subtext"> We'll get back to you soon </div>
    <div class ="download">

	  <div class="cont__row" style="background-color: #d9b44a;">
         <div class="cont__column">
              
		       <form method="POST">
                
            <label>Name</label><br> 
            <input type="text" name="name" value="<?php echo $name;?>"><br> <br> 
                
            <label>Email</label><br> 
            <input type="email" name="email" value="<?php echo $email;?>"><br> <br> 
          
        <label>Select a Category</label> <br> 
            <select name="type" id="category" size="1" value="<?php echo $type;?>">
                <option value=''>                 </option>
                <option value='Questions'>Questions</option>
                <option value="Report Problem">Report Problem</option>
                <option value='Suggestion'>Suggestion</option>
                <option value='Other'>Other</option>
                <option value="Website Problem"> Website Problem</option>
            </select>
         
            </div>
        
            <div class="cont__column">
            <label>Message</label><br> 
            <textarea name="message" rows="10" cols="50" style="font: 500 1rem sans-serif"><?php echo $message;?></textarea><br> <br> 
          
          
            <div class="button">
            <input type="image" id="myimage" src="images/email1.jpg" style="height:40px; width:160px;"/>
                
        </form>
      </div>
    </div>
  </div>
  </div> 
  <?PHP require_once("footer.php"); ?>

You were told in the other help forum how to prevent those errors. Did you actually read, understand, and use the information that someone took the time to write?

Yes, I did and everything is working properly now.

Sponsor our Newsletter | Privacy Policy | Terms of Service