Andy
Andy

Reputation: 77

Struggling with PHP validation

I have some previous experience in Python programming, but i was asked to build a web page for someone so i have tried to build a basic page using a bootstrap framework, html and php (Learning as a went along).

Everything seemed to be exactly as needed appart from the subscription form having no validation, so i thought it was best to impliment some, but the form doesnt seem to react and still allows the script to complete and send the email even with a total empty form.

Would this be because the form is in a 'Modal'? I am still quite a novice at this and i apologise if this has been covered before but i cannot find an answer that helps me.

I attach the modal form html and php code.

<!-- Modal form -->
<div class="modal fade" id="Subscribe" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Subscribe for updates!</h4>
      </div>
      <div class="modal-body">
            <div class="container-fluid">
              <form method="post" action="Submit.php">
                <div class="row">
                    <div class="col-xs-12">
                        <div class="input-group" style="margin-bottom: 5px;">
                            <span class="input-group-addon" id="first">First Name</span>
                            <input type="text" class="form-control" placeholder="John" name="first" aria-describedby="First-Name">
                            <span class="input-group-addon error" style="color: red">* <?php echo $firstErr;?></span>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-12">
                        <div class="input-group" style="margin-bottom: 5px;">
                            <span class="input-group-addon" id="last">Surname</span>
                            <input type="text" class="form-control" placeholder="Smith" name="surname" aria-describedby="Surname">
                            <span class="input-group-addon error" style="color: red">* <?php echo $lastErr;?></span>
                        </div>
                    </div>
                 </div>
                 <div class="row">
                    <div class="col-xs-12">
                        <div class="input-group" style="margin-bottom: 5px;">
                            <span class="input-group-addon" id="email">Email</span>
                            <input type="email" class="form-control" placeholder="[email protected]" name="email" aria-describedby="Email">
                            <span class="input-group-addon error" style="color: red">* <?php echo $fromErr;?></span>
                        </div>
                     </div>
                </div>
                <div class="row">
                    <div class="col-xs-12">
                        <div class="input-group" style="margin-bottom: 5px;">
                            <span class="input-group-addon" id="notes">Notes</span>
                            <textarea class="form-control" rows="3" placeholder="Please put anything else you want to say here" name="notes" aria-describedby="Notes">
            </textarea>
                        </div>
                     </div>
                </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="submit" name="submit" value="submit" class="btn btn-primary">Send</button>
              </div>
            </form>
          </div>
      </div>
    </div>
  </div>
</div>

File named 'Submit.php

<?php 

// define variables and set to empty values
$fromErr = $firstErr = $lastErr = $notesErr = "";
$from = $first_name = $last_name = $notes = "";

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

if (isset($_POST['submit'])) {
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }
  }
  if (empty($_POST["first"])) {
    $firstErr = "Name is required";
  } else {
    $first_name = test_input($_POST["first"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$first_name)) {
      $firstErr = "Only letters and white space allowed"; 
    }
  }
  if (empty($_POST["surname"])) {
    $lastErr = "Surname is required";
  } else {
    $last_name = test_input($_POST["surname"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$last_name)) {
      $lastErr = "Only letters and white space allowed"; 
    }
  }
    $notes = test_input($_POST["notes"]); // this is the senders message

    $to = "[email protected]";  // this is your Email address
    $subject = "Website subscription from " . $first_name . " " . $last_name; //Subject line

    $message = "First name: " . $first_name . "<br>" . "Surname: " . $last_name . "<br>" . "Email: " . $from . "<br>" . "Notes: " . $notes;

    $headers = "From: " . $from . "\r\n";
//  $headers .= "CC: [email protected]\n"; option to CC
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    mail($to,$subject,$message,$headers);
    header('Location: ./index.html#Thanks'); // redirect back to main page with 'Thanks' Modal open
}
?>

I would very much appreciate any help!

EDIT:

Just incase anyone wants to know how I totally ended up where I needed to be: @leepowers answer was a huge step in the right direction, this enabled me to check whether there were any errors and prevent the email sending if there were, I then learnt about 'sessions', i stored the errors in sessions (probably in a very messy way) so i could reuse them on return to the form.

// Gather all errors into an array
$errors = array($fromErr, $firstErr, $lastErr);
// Remove any empty error messages from the array
$errors = array_filter($errors);
// An array with more than zero elements evaluates `true` in a boolean context
if ($errors) {
    $_SESSION["fromErr"] = $fromErr;
    $_SESSION["firstErr"] = $firstErr;
    $_SESSION["lastErr"] = $lastErr;
    die(header('Location: ./index.html#Subscribe'));
} else { // send email

In my html page i have some JS to direct the 'redirect' into a modal:

<script>
$(document).ready(function() {

  if(window.location.href.indexOf('#Thanks') != -1) {
    $('#Thanks').modal('show');
 } else if(window.location.href.indexOf('#Subscribe') != -1) {
    $('#Subscribe').modal('show');
  }
});
</script>

and now each of my input in my form have a dedicated to errors:

<div class="input-group" style="margin-bottom: 5px;">
                        <span class="input-group-addon" id="email">Email</span>
                        <input type="email" class="form-control" placeholder="[email protected]" name="email" aria-describedby="Email">
                        <span class="input-group-addon error" style="color: red">* <?php echo $_SESSION["fromErr"];?></span>

Thank you all for the help.

Upvotes: 3

Views: 87

Answers (2)

Prateek Joshi
Prateek Joshi

Reputation: 4067

Try this, I have not validated the data ,you have to do that on your own. Also your $from was empty in the code you have posted.

   <?php
//if "email" variable is filled out, send email
  if (isset($_REQUEST['email']))  {

  //Email information
  $to = "Your_email_id";
  $email = $_REQUEST['email'];
  $first_name=$_REQUEST['first'];
  $last_name=$_REQUEST['surname'];
  $name=$first_name.' '.$last_name;
  $subject ="Your subject";
  $message = $_REQUEST['notes'];

  //send email
  mail($to, $subject, $message, "From:" . $email." Name:".$name);

  //Email response
  echo "Thank you for contacting us!";
  }

  //if "email" variable is not filled out, display the form
  else  {


  }
?>

Upvotes: 1

leepowers
leepowers

Reputation: 38318

The code needs to check for any error messages and stop execution before sending out the email. Something like the following which would be inserted after the validation checks:

// Gather all errors into an array
$errors = array($emailErr, $firstErr, $lastErr);
// Remove any empty error messages from the array
$errors = array_filter($errors);
// An array with more than zero elements evaluates `true` in a boolean context
if ($errors) {
  // Output error messages and exit the script.
  die(implode("<br>\n", $errors));
}

This is a very basic example. It would be best to initialize and $errors array at the top of the script, then add error messages to this array as they occur.

Upvotes: 1

Related Questions