hey everyone, hoping someone can help with this issues, been trying to figure it out for a few days now.

doing a basic contact page with processing in the same page and having issues with php processing script. Page throws a white page and after some searching found its a 500 server error. Server has been checked every other page works like it should. When i remove the form processing script no more server error which leads me to something in script is the cause.


<?php

// Define variables and set to empty values

$result  = $name = $email = $phone = $message = $human = "";
$errName = $errEmail = $errPhone = $errMessage = $errHuman = "";
if (isset($_POST["submit"])) {
				$name    = $_POST['name'];
				$email   = $_POST['email'];
				$phone   = $_POST['phone'];
				$message = $_POST['message'];
				$human   = intval($_POST['human']);
				$from    = 'system@1232.com';
				$to      = 'test@mydomain.com';
				$subject = 'Message From Contact Page';
				$headers = "From:$from\r\nReply-to:$email";
				$body    = "From: $name\n E-Mail: $email\n Phone: $phone\n Message: $message";
} 


// Check if name is entered
if (empty($_POST["name"])) {
				$errName = "Please enter your name.";
} 

//empty($_POST["name"])

else {
				$name = test_input($_POST["name"]);
}
if (empty($_POST["phone"])) {
				$errName = "Please enter your phone number.";
} 

//empty($_POST["phone"])

else {
				$name = test_input($_POST["name"]);
}
// Check if email is entered

if (empty($_POST["email"])) {
				$errEmail = "Please enter your email address.";
} 

//empty($_POST["email"])

else {
				$email = test_input($_POST["email"]);
				// check if e-mail address is valid format
				if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
								$errEmail = "Invalid email format.";
				} //!filter_var($email, FILTER_VALIDATE_EMAIL)

}

//Check if message is entered
if (empty($_POST["message"])) {
				$errMessage = "Please enter your message.";
} 

//empty($_POST["message"])

else {
				$message = test_input($_POST["message"]);
}

//Check if simple anti-bot test is entered
if (empty($_POST["human"])) {
				$errHuman = "Please enter the sum.";
} 

//empty($_POST["human"])

else {
				if ($human !== 12) {
								$errHuman = 'Wrong answer. Please try again.';
				} //$human !== 12
}
//sanitize data inputs   
function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); $data = (filter_var($data, FILTER_SANITIZE_STRING)); return $data; } // If there are no errors, send the email & output results to the form if (!$errName && !$errEmail && !$errPhone && !$errMessage && !$errHuman) { if (mail($to, $subject, $body, $from)) { $result = '<div class="alert alert-success"><h2><span class="glyphicon glyphicon-ok"></span> Message sent!</h2><h3>Thank you for contacting us. Someone will be in touch within in 1 business day.</h3></div>'; } //mail($to, $subject, $body, $from) else { $result = '<div class="alert alert-danger"><h2><span class="glyphicon glyphicon-warning-sign"></span> Sorry there was a form processing error.</h2> <h3>Please try again later.</h3></div>'; } } //sanitize data inputs
function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); $data = (filter_var($data, FILTER_SANITIZE_STRING)); return $data; } //end form processing script ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Contact US</title> ......

And the form:

 <!-- Contact Us -->
        <div class="contact-us-container">
            <div class="container">
                <div class="row">
                    <div class="col-sm-7 contact-form wow fadeInLeft">
                        <p>
                            <!--when submit button is clicked, show results here-->
                        <div class="form-group">
                            <div class="col-sm-10"> <?php echo $result;?> </div>
                        </div>
                        </p>
                        <form role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
                            <div class="form-group">
                                <label for="contact-name">Name</label>
                                <span class="required">*</span>
                                <input type="text" name="name" placeholder="Enter your name..." class="contact-name" id="contact-name" value="<?php echo $name;?>">
                                <span class="required small"><?php echo $errName;?></span> 
                            </div>
                            <div class="form-group">
                                <label for="contact-email">Email</label>
                                <span class="required">*</span>
                                <input type="text" name="email" placeholder="Enter your email..." class="contact-email" id="contact-email" value="<?php echo $email;?>">
                                <span class="required small"><?php echo $errEmail;?></span> 
                            </div>
                            <div class="form-group">
                                <label for="contact-phone">Phone</label>
                                <span class="required">*</span>
                                <input type="text" name="phone" placeholder="Enter your phone..." class="contact-phone" id="contact-phone" value="<?php echo $phone;?>">
                                <span class="required small"><?php echo $errPhone;?></span> 
                            </div>
                            <div class="form-group">
                                <label for="contact-subject">Subject</label>
                                <span class="required">*</span>
                                <input type="text" name="subject" placeholder="Your subject..." class="contact-subject" id="contact-subject" value="<?php echo $subject;?>">
                                <span class="required small"><?php echo $errSubject;?></span> 
                            </div>
                            <div class="form-group">
                                <label for="contact-message">Message</label>
                                <span class="required">*</span>
                                <textarea name="message" placeholder="Your message..." class="contact-message" id="contact-message" value="<?php echo $message;?>"></textarea>
                                <span class="required small"><?php echo $errMessage;?></span> 
                            </div>
                            <div class= "form-group">
                                <label for="human">Human Test</label>
                                <span class="required">*</span>
                                <p>6 + 6 = ?</p>
                                <input type="text" class="contact-human" id="human" name="human" placeholder="Your Answer..." value="<?php echo $human;?>">
                                <span class="required small"><?php echo $errHuman;?></span> 
                            </div>
                            <button type="submit" class="btn">Send</button>
                        </form>
                    </div>

    A couple thoughts:

    All the form processing stuff should probably be in some sort of if() block that only runs if it detects that the form has actually been submitted.

    However, I suspect your immediate problem is that you try to define the function test_input() twice, and that's going to throw a parse error before anything further happens.

      turned error reporting on and got error related to test_input

      Fatal error: Cannot redeclare test_input() (previously declared in public_html/contact.php:81) in /public_html/contact.php on line 108. Fixed that issue.

      now having issue with anti bot part of form ( human field, $human)

      Even with entering correct answer still trips $errHuman = 'Wrong answer. Please try again.'; clause

      updated code: see green

      <?php
      
      // Define variables and set to empty values
      
      $result  = $name = $email = $phone = $message = $human = "";
      $errName = $errEmail = $errPhone = $errMessage = $errHuman = "";
      if (isset($_POST["submit"])) {
      				$name    = $_POST['name'];
      				$email   = $_POST['email'];
      				$phone   = $_POST['phone'];
      				$message = $_POST['message'];
      				$human   = intval($_POST['human']);
      				$from    = 'system@1232.com';
      				$to      = 'test@mydomain.com';
      				$subject = 'Message From Contact Page';
      				$headers = "From:$from\r\nReply-to:$email";
      				$body    = "From: $name\n E-Mail: $email\n Phone: $phone\n Message: $message";
      } 
      
      
      // Check if name is entered
      if (empty($_POST["name"])) {
      				$errName = "Please enter your name.";
      } 
      
      //empty($_POST["name"])
      
      else {
      				$name = test_input($_POST["name"]);
      }
      
      //Check if phone is entered
      if (empty($_POST["phone"])) {
      				$errPhone = "Please enter your phone number.";
      } 
      
      //empty($_POST["phone"])
      
      else {
      				$name = test_input($_POST["phone"]);
      }
      
      // Check if email is entered
      
      if (empty($_POST["email"])) {
      				$errEmail = "Please enter your email address.";
      } 
      
      //empty($_POST["email"])
      
      else {
      				$email = test_input($_POST["email"]);
      				// check if e-mail address is valid format
      				if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      								$errEmail = "Invalid email format.";
      				} //!filter_var($email, FILTER_VALIDATE_EMAIL)
      
      }
      
      //Check if message is entered
      
      if (empty($_POST["message"])) {
      				$errMessage = "Please enter your message.";
      } 
      
      //empty($_POST["message"])
      
      else {
      				$message = test_input($_POST["message"]);
      }
      
      //Check if simple anti-bot test is entered
      
      if (empty($_POST["human"])) {
      				$errHuman = "Please enter the sum.";
      } 
      
      //empty($_POST["human"])
      
      else {
      				if ($human !== 12) {
      								$errHuman = 'Wrong answer. Please try again.';
      				} //$human !== 12
      }
      //sanitize data inputs   
      
      function test_input($data)
      {
      				$data = trim($data);
      				$data = stripslashes($data);
      				$data = htmlspecialchars($data);
      				$data = (filter_var($data, FILTER_SANITIZE_STRING));
      				return $data;
      }
      
      // If there are no errors, send the email & output results to the form
      if (!$errName && !$errEmail && !$errPhone && !$errMessage && !$errHuman) {
      				if (mail($to, $subject, $body, $from)) {
      								$result = '<div class="alert alert-success"><h2><span class="glyphicon glyphicon-ok"></span> Message sent!</h2><h3>Thank you for contacting us. Someone will be in touch within in 1 business day.</h3></div>';
      				} //mail($to, $subject, $body, $from)
      				else {
      								$result = '<div class="alert alert-danger"><h2><span class="glyphicon glyphicon-warning-sign"></span> Sorry there was a form processing error.</h2> <h3>Please try again later.</h3></div>';
      				}
      } 
      
      
      //end form processing script
      ?>

        As you're intval'ing $_POST['human'], there's little point in checking to see if it's set again.

        if ($human != 12) $errHuman = "Go away bot!";

          The problem is because the $human variable isn't being set at all, because there is no form field that's setting - $_POST["submit"], and the top conditional piece of php code is being skipped over, combined with the fact that ALL the form processing code should be inside that conditional statement.

            pbismad;11056357 wrote:

            there is no form field that's setting - $_POST["submit"]

            Good catch ...

              I've seen this style of form processing code a lot recently. I don't know if it comes up on the top web searches or if Instructors are actively using this in courses. This style of coding, with discrete variables and same blocks of code, repeated for each different form field, produces a wall of repetitive, error prone, logic, making it hard to see what you are really doing (cannot see the forest for the trees problem.) You are spending a majority of your time beating on a keyboard, typing/copy/pasting the same things over and over, rather than concentrating on the logic and program flow you need, to accomplish the task.

              In addition to the logic error, where not all of the form processing code is inside the if(){...} conditional statement, you have a 'Subject' field in the form that is not being used in the form processing code. Doing the following will help make sure that any form field gets processed, or if you don't want the field at all, removing it from the design will be easy, and since this will reduce the amount of code that exists, it will make seeing what your program logic actually is doing, easier.

              While the following sounds like an advanced programming topic, all it requires is understanding array variables (a variable that has more than one dimension), a few of php's array functions/loops, and a little indirect thinking. If you have more than about 2-3 of anything in programming, you need to dynamically process the data or produce the output as a set, using a data driven design. This means defining a data structure somewhere (array, database table) that tells your code what to do. The code then becomes simple and general purpose since it only needs to know how to do each different thing, not know specifically what to do to each piece of data.

              If you had an array like the following -

              $fields = array();
              // the main array key/index is the field name, the array holds settings that define things about each field
              // 'label' is used to produce messages and could be used as the label for the form field, if you dynamically produce the form
              // 'required' is used by the logic to check if the field is required to be a non-empty value
              // 'email' is used by the logic if the field should be added to the email body
              $fields['name'] = array('label'=>'Name','required'=>'y','email'=>'y'); 
              $fields['email'] = array('label'=>'Email','required'=>'y','email'=>'y'); 
              $fields['phone'] = array('label'=>'Phone Number','required'=>'y','email'=>'y'); 
              $fields['message'] = array('label'=>'Message','required'=>'y','email'=>'y');
              $fields['human'] = array('label'=>'Sum','required'=>'y'); 

              You could simply loop over this array in the form processing code and use the 'required' setting to control if a an empty form field produces a "Please enter the ..." message (the 'label' value is used as the ... in the message.) For example, like this -

              // check all required fields
              // note: $data is an array that holds a copy of all the trimmed $_POST data. $errors is an array that you put error messages into. These arrays replace the lists of discrete variables in the current code.
              foreach($fields as $field=>$arr)
              {
              	if(isset($arr['required']) && $arr['required'] == 'y' && $data[$field] == '')
              	{
              		$errors[$field] = "Please enter the {$arr['label']}.";
              	}
              }

              This code will work no matter how many form fields there are and you don't need to touch this code when the number of form fields gets changed. You can expand upon this method to handle other specific validation for any field or you can continue to use discrete logic for field(s), which ever is simpler for what you are doing.

              If you expand upon this method and add a 'type'=>'text' or 'type'=>'textarea' entry to the defining array, you can now dynamically produce the form fields, by simply looping over this array. You would have a switch/case statement to produce the different syntax for the different type of fields (BTW, you have an error in your textarea field. There is no value='...' attribute for a textarea. You output any existing value between the <textarea>existing content goes here...</textarea> tags). This will mean that your form will only have the fields that you have defined and that all the fields in the form will be processed by the processing code. Adding or removing a field will be easy, just add or remove the entry in the defining array.

                thank you pbismad i have been banging my head since yesterday, that def would clean things up a bit, gonna go work on and see where it goes, will post back with an update

                  ok, have been up all night trying to wrap my head around array's with out much luck, gonna keep reading up on that. In the mean time have simplified code back to basics and will add in validation after sorting this issue out.

                  Form and processing works, get message in my inbox the way suppose to at least with current scripting.

                  am getting a single notice

                  Notice: Undefined variable: Body in /home/myserver/public_html/post.php on line 24

                  <?php
                  
                  //processing script v7 
                  
                  if($_SERVER['REQUEST_METHOD'] == "POST")   {
                  $name = $_POST["name"];
                  $email = $_POST["email"];
                  $phone =  $_POST["phone"];
                  $message = $_POST["message"];
                  
                  }else{ 
                  
                  echo "Form Data not reaching processing script. No Data in POST"; // testing
                  }
                  
                  
                  // define addresses
                  
                  $EmailTo = "test@domain.com";
                  $EmailFrom = "123@domain.com";
                  $Subject = "New Message Received";
                  
                  // prepare email body text temp code 
                  $Body .= "Name: ";   // line 24 
                  $Body .= $name;
                  $Body .= "\n";
                  
                  $Body .= "Email: ";
                  $Body .= $email;
                  $Body .= "\n";
                  
                  $Body .= "Phone: ";
                  $Body .= $phone;
                  $Body .= "\n";
                  
                  $Body .= "Message: ";
                  $Body .= $message;
                  $Body .= "\n";
                  
                  
                  $success = mail($EmailTo, $Subject, $Body, "From:".$EmailFrom);
                   // If there are no errors, send the email
                  
                  	if ($success) {
                  
                  	$success='<div class="alert alert-success"><h2><span class="glyphicon glyphicon-ok"></span> Message sent!</h2><h3>Thank you for contacting us. Someone will be in touch with you soon.</h3></div>;';
                  
                  } else {
                  
                  	$success='<div class="alert alert-danger"><h2><span class="glyphicon glyphicon-warning-sign"></span> Sorry there was a form processing error.</h2><h3>Please try again later.</h3></div>;';
                  }
                  
                  
                  ?>
                  

                  i dont understand how body is Undefined variable, yet still processes fine and i get in my inbox? Can someone shine some light on this?

                  I know there is probability a better way of doing this, but still learning array's and couldn't get script working right that pbismad posted, something simple i am sure but like I said still learning.

                    For the first assignment to $Body, just use the "=" operator, as ".=" is trying to append it to an existing variable, which does not exist yet the first time.

                      PS: You could simply do:

                      $Body = "Name: $name
                      mail: $email
                      "; 
                      

                        thanks nog dog. i knew it was something simple a freaking period.

                          Write a Reply...