Jump to content

Small Issue With Inquiry Form Script


trg86

Recommended Posts

Hello everybody! I hope you are doing great!

 

I am having a small issue with the script I have been building most of the day today. Everything is working fine except for the mailing of the form and the redirect. Upon submission of the form, it just reloads itself as a blank form and nothing happens.

 

I have attached my script below for reference to helping me resolve my issue. The only part I edited out was the actual email part of the script as it is not relevant for this issue and I wanted to keep the reading of my code as short as possible.

 

I am a code organizing and commenting nut, so hopefully my coding is easy to read and understand for you.

 

Thank you in advance for the help!

<?php
//*********************//
// Filter Input Values //
//*********************//
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//**********************************//
//    Initialize All Variables      //
//              NULL                //
//**********************************//
$name = "";           // Users Name
$email = "";          // Users E-Mail Address
$phone_number = "";   // Users Phone Number
$contact_method = ""; // Users Preferred Contact Method
$phone_consent = "";  // Users Consent To Receive Phone Call
$best_time = "";      // Best Time To Reach User
$referrer = "";       // Users Referrer
$message = "";        // Users Message
$nameError = "";               // Name Error
$emailError = "";              // Email Error
$phone_numberError = "";       // Phone Number Error
$contact_methodError = "";     // Preferred Contact Method Error
$phone_consentError = "";      // Phone Call Consent Error
$best_timeError = "";          // Best Time To Reach Error
$referrerError = "";           // Referrer Error
$messageError = "";            // Message Error
//*********************************//
//   Initialize Validation Rules   //
//*********************************//
if(isset($_POST['submit']))
{
// Contact Method Validation
if (empty($_POST["contact_method"])){
$contact_methodError = "How Would You Like Us To Contact You?";
}
// Phone Consent Validation
if (empty($_POST["phone_consent"])){
$phone_consentError = "Do We Have Permission To Call You?";
}
// Best Time To Contact Validation
if (empty($_POST["best_time"])){
$best_timeError = "What Is The Best Time For Us To Reach You?";
}
// Referrer Validation
if (empty($_POST["referrer"])){
$referrerError = "How Did You Hear About Us?";
}    
// Name Input Validation
if (empty($_POST["name"])){
$nameError = "Your Name Is Required";
}
else
 {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError = "Only Letters And White Space Allowed";
}
}
// Email Input Validation
if (empty($_POST["email"])){
$emailError = "Please Enter Your Email Address";
}
else
 {
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$emailError = "The Email You Entered Is Not Valid";
}
}
// Phone Number Input Validation
if (empty($_POST["phone_number"]))
{
$phone_numberError = "Please Enter A Valid Phone Number";
}
else
{
$phone_number = test_input($_POST["phone_number"]);
}
// Message Input Validation
if (empty($_POST["message"]))
{
$messageError = "What Are You Contacting Us About?";
}
else
 {
$message = test_input($_POST["message"]);
if (!preg_match("/^[a-zA-Z ]*$/",$message))
{
$messageError = "Only Letters And White Space Allowed";
}
 }
// Check For Any Null Values
if( !($name=='') && !($email=='') && !($phone_number=='') && !($contact_method=='') && !($phone_consent=='') && !($best_time=='') && !($referrer=='') && !($message=='') )
{
$recipients = "EDITEDOUT@FORTHISPOST.COM";                    //E-Mail Recipient(s)
$subject = "New Message Received";    //E-Mail Subject Line
$body = " EDITED THIS PART OUT TO SAVE SPACE IN THIS POST";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: no-reply@EDITEDOUTFORTHISPOST.com\r\n";
$headers .= "Return-Path: no-reply@EDITEDOUTFORTHISPOST.com\r\n";
if(mail($recipients,$subject,$body,$headers)){
header('Location: success.php');     //USER REDIRECT AFTER SUCCESSFUL FORM SUBMISSION ( CONFIRMATION PAGE )
}
}
}
?>

 

Link to comment
Share on other sites

what's wrong, that's causing the current symptom (there are other problems too), is that you are not setting at least one of your variables from the submitted form data, so the big long if(...) statement is false and the code at the end is being skipped over.

 

you need to constantly process each input (so that none of them get forgotten and you are not testing different versions of the same value), get rid of the test_input() function (it's from the web, improperly named, and improperly coded for what you are doing), and if you are up to it, use a data driven design that will simplify all the code, by creating an array that defines the expected form fields and what validation each field uses, that you would loop over to dynamically operate on the data, rather than to write out block after block of bespoke code for each possible input.

 

to start with, use an array for the errors. to initialize it, just use $errors = []; add error messages to the array in the validation logic. when you are finished with the validation, if the errors array is empty, you can use the form data. this will eliminate the big long bespoke if(....) statement that you have now.

 

there's also no good reason to create a bunch of variables, one for each possible field. just use an array variable to hold any modified version of the submitted $_POST data (it's generally a good idea to leave the original, un-modified submitted data in $_POST.)

 

you should first trim all the input data, so that you can detect if all white-space characters have been submitted, then validate the trimmed data. when you are actually using the data, is when you would apply htmlentities() to the values.

 

the defining of an array/data driven design, while it sounds like an advanced subject, only requires a little abstraction (one level) of coding, since the defining array will hold values that get used by the code to control what it does.

 

the if() test for the mail() statement, needs an else() term to cause an error when the mail call fails. in general, when validating/operating on a user submission, you need to always do something when the code doesn't do what is expected.

 

in short, get rid of the test_input() function, get rid of all those variables, trim() the data (all at once - if i have time, i'll show you a single statement that can do this), validate the data, then use the data if there are no validation errors.

 

if i/someone has time, they will post an example.

Link to comment
Share on other sites

here is a quick/minimal example - 

<?php

$errors = []; // an array to hold errors
$data = []; // an array to hold a working copy of the submitted data

$fields = []; // the defining structure of the form fields/validation

// i'm guessing the following fields are/should-be radio button choices and some should have default values and wouldn't be not-set?
$fields["contact_method"] = ['label'=>'','required'=>'','regex'=>'','regex_error'=>''];
$fields["phone_consent"] = ['label'=>'','required'=>'','regex'=>'','regex_error'=>''];
$fields["best_time"] = ['label'=>'','required'=>'','regex'=>'','regex_error'=>''];
$fields["referrer"] = ['label'=>'','required'=>'','regex'=>'','regex_error'=>''];

// text and textarea fields
$fields["name"] = ['label'=>'Name','required'=>'y','regex'=>'/^[a-zA-Z ]*$/','regex_error'=>'may only contain letters and spaces']; // there are names that have more than letters and spaces
$fields["email"] = ['label'=>'Email','required'=>'y','regex'=>'/([\w\-]+\@[\w\-]+\.[\w\-]+)/','regex_error'=>'is an invalid format'];
$fields["phone_number"] = ['label'=>'Phone Number','required'=>'y','regex'=>'','regex_error'=>''];
$fields["message"] = ['label'=>'Message','required'=>'y','regex'=>'/^[a-zA-Z ]*$/','regex_error'=>'may only contain letters and spaces']; // needs to allow some punctuation


// form processing
if($_SERVER['REQUEST_METHOD'] == 'POST') // use a generic method to detect if the form was submitted
{
    $data = array_map('trim',$_POST); // get a trimmed copy of all 1st level (non-array) form data. if any of your form fields are arrays, write a call-back function and use array_walk_recursive() instead.
    
    // validate data
    foreach($fields as $field=>$arr)
    {
        $value = $data[$field];
        // if required
        if($arr['required'] == 'y' && $value == '')
        {
            $errors[$field] = "{$arr['label']} is required.";
        }
        
        // if regex pattern
        if($arr['regex'] && $value != '' && !preg_match($arr['regex'],$value))
        {
            $errors[$field] = "The {$arr['label']} {$arr['regex_error']}.";
        }
    }
    
    // if no errors, use the form data
    if(empty($errors))
    {
        $recipients = "EDITEDOUT@FORTHISPOST.COM";                    //E-Mail Recipient(s)
        $subject = "New Message Received";    //E-Mail Subject Line
        
        // apply htmlentities() to all data being used
        $email_data = array_map('htmlentities',$data); // note: this uses the default parameters for htmlentities. if you need to use different values, create a call-back function and use it in the array_map() call.
        
        $body = " EDITED THIS PART OUT TO SAVE SPACE IN THIS POST";

        $headers = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
        $headers .= "From: no-reply@EDITEDOUTFORTHISPOST.com\r\n";
        $headers .= "Return-Path: no-reply@EDITEDOUTFORTHISPOST.com\r\n";
        if(mail($recipients,$subject,$body,$headers))
        {
            header('Location: success.php');     //USER REDIRECT AFTER SUCCESSFUL FORM SUBMISSION ( CONFIRMATION PAGE )
            die; // header redirect needs a die to stop execution so that the rest of the code isn't executed
        }
        else
        {
            $errors[] = 'The mail call failed.'; // your live server should be set up to log all php errors, but you can also capture the last php error, immediately after the mail() call, and use that here.
        }
    }
}


// code producing the web page

// output any errors here...
if(!empty($errors))
{
    echo implode('<br>',$errors); 
}


// make a form for testing (all fields are type='text') - to apply the data driven design to this, you would add elements in the $fields array entries to tell this section of code what to do
echo "<form method='post'>\n";

// apply htmlentities() to all data being used
$form_data = array_map('htmlentities',$data); // note: this uses the default parameters for htmlentities. if you need to use different values, create a call-back function and use it in the array_map() call.

foreach($fields as $field=>$arr)
{
    echo "<label>{$arr['label']}: <input type='text' name='$field' value='". (isset($form_data[$field]) ? $form_data[$field]: '')."'></label><br>\n";
}
echo "<input type='submit'></form>";
Link to comment
Share on other sites

Thank you very much for your detailed reply. I am going to work with your example and see what I can do.

 

Just for reference, is there anything I need to do with the $fields variable? Also, my processor script is within its own file that is called upon when needed by the form submission with an "include" statement, I don't program my processor and form onto the same php page.

 

Also, in answer to your assumption about some of the fields, several are drop-down options; not radio button options. Here is the code from the page that holds the form needing to be filled out:

<?php include 'processor-1-0-0.php';?>
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="css/main_dev.css">
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container-wrapper">
<div class="container">
<div class="row">
<div class="col-sm-4 col-sm-offset-8">
<div class="contact-form">
<h3>Contact Us</h3>
<form id="main-contact-form" role="form" name="contact-form" method="post" action="contact-us.php">
<div class="form-group">
<input type="text" id="name" name="name" class="form-control" value="" placeholder="Enter Your Name">
<span><?php echo $nameError;?></span>
</div>
<div class="form-group">
<input type="email" id="email" name="email" class="form-control" placeholder="E-Mail Address" value="">
<span class="error"><?php echo $emailError;?></span>
</div>
<div class="form-group">
<input type="phone" id="phone_number" name="phone_number" class="form-control" placeholder="Phone Number (No Dashes)" value="">
<span class="error"><?php echo $phone_numberError;?></span>
</div>
<div class="form-group">
<b><small>What Is Your Preferred Contact Method?</small></b>
<select class="form-control" id="contact_method" name="contact_method">
<option value="" selected>Please Select</option>
<option value="E-Mail">E-Mail</option>
<option value="Phone">Phone</option>
</select>
<span><?php echo $contact_methodError;?></span>
</div>
<div class="form-group">
<b><small>May We Contact You At The Phone Number Provided?</small></b>
<select class="form-control" id="phone_consent" name="phone_consent">
<option value="" selected>Please Select</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<span><?php echo $phone_consentError;?></span>
</div>
<div class="form-group">
<b><small>What Is The Best Time To Reach You?</small></b>
<select class="form-control" id="best_time" name="best_time">
<option value="" selected>Please Select</option>
<option value="Morning">Morning</option>
<option value="Afternoon">Afternoon</option>
<option value="Evening">Evening</option>
</select>
<span><?php echo $best_timeError;?></span>
</div>
<div class="form-group">
<b><small>How Did You Hear About Us?</small></b>
<select class="form-control" id="referrer" name="referrer">
<option value="" selected>Please Select</option>
<option value="Google">Google</option>
<option value="Bing">Bing</option>
<option value="Yahoo">Yahoo</option>
<option value="Facebook">Facebook</option>
<option value="Twitter">Twitter</option>
<option value="Newspaper">Newspaper</option>
<option value="Friend">Friend</option>
<option value="Word of Mouth">Word of Mouth</option>
<option value="Driving By">Driving By</option>
<option value="Other">Other</option>
</select>
<span><?php echo $referrerError;?></span>
</div>
<div class="form-group">
<textarea id="message" name="message" class="form-control" rows="4" placeholder="How Can We Help You?" value=""></textarea>
<span><?php echo $messageError ?></span>
</div>
<button type="submit" name="submit" id="submit" class="btn btn-primary">Send Message</button>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.