Advanced PHP Form Validation

Last year I wrote an article in how to implement basic validation for a form with PHP. I decided to re-look at this and improve what I did in that article. This time we are going to make a more advanced PHP form that is more responsive and effective.

This PHP sample code has many advantages over the previous article. Not only that, but for the most part it is easier to implement with more complexed forms where you need more than basic validation.

Requirements

Below are the requirements for the code included in this PHP form tutorial:

JavaScript has become standard in browsers, which makes client side form validation user friendly before submitting the form. In fact, in most cases, it is the standard for form validation on the web.

With that said, I do not recommend depending on client side validation for your forms…mainly in defending against hackers and bots. But most people who use your form should have JavaScript enabled.

You can view a demo of the PHP form in action. You will not only see the standard validation (email, phone, and required fields), but we also take it a step further by validating check boxes. If the visitor checks the newsletter option, they must then check two topics before the form can be submitted (in the same way, you can do something like this with radio buttons). If there are errors in the form, and those errors are corrected, they will immediately disappear.

I took an example from the jQuery validation documentation and tweaked it a little bit to fit the form, for this PHP tutorial.

Form HTML Page

Below is the html for the page where the form will sit.

<html>
<head>
<script type="text/javascript" src="js/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="js/jquery.validate.min.js"></script>
<script type="text/javascript" src="js/additional-methods.min.js"></script>

<style type="text/css">
label { 
	float: left; 
	padding-right:10px;
}
label.error { 
	float: none; 
	color: red; 
	padding-left: .5em; 
	vertical-align: top; 
}
p { 
	clear: both; 
}
.gray { 
	/*color: gray;*/
	display: none;
}
#newsletter_topics label.error {
	display: none;
	padding-left: 0px;
}
</style>


<script type="text/javascript">
$(document).ready(function(){
	// validate signup form on keyup and submit
	$("#signupForm").validate({
		rules: {
			firstname: "required",
			lastname: "required",
			email: {
				required: true,
				email: true
			},
			phone: {
				required: true,
				phoneUS: true
			},
			agree: "required",
			'topic[]': {
				required: "#newsletter:checked",
				minlength: 2
			}
		},
		messages: {
			firstname: "Please enter your firstname.",
			lastname: "Please enter your lastname.",
			email: "Please enter a valid email address.",
			phone: "Please specify a valid phone number.",
			agree: "Please accept our policy."
		}
	});
	
	//code to hide topic selection, disable for demo
	var newsletter = $("#newsletter");
	
	// newsletter topics are optional, hide at first
	var inital = newsletter.is(":checked");
	var topics = $("#newsletter_topics")[inital ? "removeClass" : "addClass"]("gray");
	var topicInputs = topics.find("input").attr("disabled", !inital);
	
	// show when newsletter is checked
	newsletter.click(function() {
		topics[this.checked ? "removeClass" : "addClass"]("gray");
		topicInputs.attr("disabled", !this.checked);
	});
});
</script> 

</head>
<body>

<form id="signupForm" method="POST" action="processform.php"> 
	<fieldset> 
		<legend>Signup Form</legend> 
		<p> 
			<label for="firstname">*Firstname:</label> 
			<input id="firstname" name="firstname" /> 
		</p> 
		<p> 
			<label for="lastname">*Lastname:</label> 
			<input id="lastname" name="lastname" /> 
		</p> 
		<p> 
			<label for="email">*Email:</label> 
			<input id="email" name="email" /> 
		</p> 
		<p> 
			<label for="phone">*Phone Number:</label> 
			<input id="phone" name="phone" /> 
		</p> 
		
		<p>[ENTER POLICY HERE]</p>
		<p> 
			<label for="agree">*Do you agree to our policy?</label> 
			<input type="checkbox" class="checkbox" id="agree" name="agree" /> 
		</p>
		
		<p> 
			<label for="newsletter">Would you like to receive our newsletter?</label> 
			<input type="checkbox" class="checkbox" id="newsletter" name="newsletter" /> 
		</p> 
		<fieldset id="newsletter_topics"> 
			<legend>Topics (select at least two) - note: would be hidden when newsletter isn't selected, but is visible here for the demo</legend> 
			<label for="topic_marketflash"> 
				<input type="checkbox" id="topic_marketflash" value="marketflash" name="topic[]" /> 
				Marketflash
			</label> 
			<label for="topic_fuzz"> 
				<input type="checkbox" id="topic_fuzz" value="fuzz" name="topic[]" /> 
				Latest fuzz
			</label> 
			<label for="topic_digester"> 
				<input type="checkbox" id="topic_digester" value="digester" name="topic[]" /> 
				Mailing list digester
			</label> 
			<label for="topic[]" class="error"><br /><br />Please select at least two topics you'd like to receive.</label> 
		</fieldset> 
		<p> 
			<input class="submit" type="submit" value="Submit"/> 
		</p> 
	</fieldset> 
</form> 

</body>
</html>

One thing you will notice is that there is no PHP code on this page. You will also notice that jQuery is used heavily. In the head tag we define which fields are required and the error messages to display if the field is not entered correctly. This is the largest improvement over the last form example, since the client side error handling is immediate and it displays the errors without posting the form. There was no client side validation in the previous PHP form article.

If you are not familiar in working with jQuery, I highly recommend going through some basic jQuery examples. The bundled code I provide at the end of this PHP tutorial includes the jQuery files necessary in making this example work.

PHP: Process the Form

Since jQuery is JavaScript, if the visitor has JavaScript disabled, the validation on this page will not work and the form will be posted. With this in mind, we still need to do server side validation. I took the code that was used in the previous tutorial, and improved it for this example.

<?php 
/*
 * BEGIN CONFIG
 */

// The page you want the user to be redirected if there are no errors.
$thankYouPage = 'thanks.html';

// Define which values we are to accept from the form. If you add additional 
// fields to the form, make sure to add the form name values here.
$allowedFields = array(
	'firstname', 
	'lastname',
	'email',
	'phone',
	'agree',
	'newsletter',
	'topic',
);

// Specify the required form fields. The key is the field name and the value 
// is the error message to display.
$requiredFields = array(
	'firstname' => 'First name is required.', 
	'lastname' => 'Last name is required.',
	'email' => 'Email address is required.',
	'phone' => 'Phone number is required.',
	'agree' => 'You must agree with our policy.',
);

// Note: Since we are requiring two topics to be checked if they want to receive 
// our newsletter, we need to implement custom code.

/*
 * END CONFIG
 */


/*
 * Since we are doing javascript error checking on the form before the form gets submitted, 
 * the server side check is only a backup if the user has javascript disabled. Since this 
 * is unlikely, we are displaying the server side errors on a separate page of the form.
 * 
 * The more practical purpose of server side checking (in this case) is to prevent hackers from exploiting 
 * your PHP processing code.
 */


/*
 * BEGIN FORM VALIDATION
 */

$errors = array();

// We need to loop through the required variables to make sure they were posted with the form.
foreach($requiredFields as $fieldname => $errorMsg)
{
	if(empty($_POST[$fieldname]))
	{
		$errors[] = $errorMsg;
	}
}

// Loop through the $_POST array, to create the PHP variables from our form.
foreach($_POST AS $key => $value)
{
    // Is this an allowed field? This is a security measure.
    if(in_array($key, $allowedFields))
    {
        ${$key} = $value;
    }
}

// Code to validate the newsletter topic checkboxes
if(!empty($_POST['newsletter']))
{
	// They checked the newsletter checkbox...make sure they 
	// checked at least two topics.
	if(count($_POST['topic']) < 2)
	{
		$errors[] = "In order to receive our newsletter, you must check at least two topics.";
	}
}

/*
 * END FORM VALIDATION
 */


// Were there any errors?
if(count($errors) > 0)
{
    $errorString .= '<ul>';
    foreach($errors as $error)
    {
        $errorString .= "<li>$error</li>";
    }
    $errorString .= '</ul>';
 
    // display the errors on the page
    ?>
    <html>
    <head>
    <title>Error Processing Form</title>
    </head>
    <body>
    <h2>Error Processing Form</h2>
    <p>There was an error processing the form.</p>
    <?php echo $errorString; ?>
    <p><a href="index.php">Go Back to the Form</a></p>
    </body>
    </html>
    <?php 
}
else
{
    // At this point you can send out an email or do whatever you want
    // with the data...
 
    // each allowed form field name is now a php variable that you can access
 
    // display the thank you page
    header("Location: $thankYouPage");
}
?>

A configuration area was added to the beginning of the file. Notice that in this code, if there is are no errors processing the form, we display the errors on this page instead of the previous form. This does several things:

1. Since the majority of people will have JavaScript enabled, the server side form validation is only meant as a backup and to prevent hackers from trying to exploit the form. So displaying errors on a blank page should suffice in this case. With that said, there may be times were going back to the form and pre-populating the fields makes sense.

2. This simplifies things. We don’t have to use PHP on the form html page at all.

I also do not use the short tag version of calling PHP for compatibility.

You can download all of the PHP Form Code, which includes the required JavaScript files.

38 thoughts on “Advanced PHP Form Validation

  1. Advanced PHP Form Validation…

    Last year I wrote an article in how to implement basic validation for a form with PHP. I decided to re-look at this and improve what I did in that article. This time we are going to make a more advanced PHP form that is more responsive and effective….

    Like

  2. Here is another php forms tutor: phpforms.net/tutorial, you can also see a video there, that will help you to understand how to build web forms easily and quickly.

    Like

  3. Good idea and good explanation. The validate plugin really changes the flow of the application. You’ve simplified the validation and error handling. I think I’d use php on the form page for token generation… Good contribution to the community.

    Like

    • Thanks for your comment Joel. You could use PHP to generate dynamic JavaScript if you needed to on the form page. This opens up a lot of options and the ability in creating complex systems/.

      Like

  4. This is not an advanced tutorial, and you are not an advanced php programmer. It’s good that you want to share knowledge with people, but you need to take a step back and not be so over-confident in your own ability.

    None of the code you have written here is particularly re-usable. What if I want to do the same validation on 10 different pages on my website? Do I just copy the same code 10 times? That would lead to a mess.

    You’re also mixing presentation with the logic of the program, which is a horrible, horrible thing to do.

    Much better would be to create objects that represent form elements, and extend each object in your library to represent common types of form fields. So for example, you may have an EmailElement type that extends FormElement. FormElement could be an abstract class that would have say an isValid() abstract method, so all child elements would be required to implement this method. The EmailElement implementation of this could then be a decent regular expression to work out whether the input from the user was an email address or not.

    You could then use that EmailElement component on ANY page that required an email address, and the code would be clean and seperate from any presentation logic.

    You’d end up with a snippit like this:

    $userInputEmail = $_GET[’email’];

    $emailElement = new EmailElement();

    if (!$emailElement->isValid()){
    $emailElement->getError();
    }

    You could put the getError() method in the abstract superclass too.

    With a few tweaks, this could become powerful, and would be really and truly reusable code.

    See, it’s already been done. Look:

    http://framework.zend.com/manual/en/zend.form.elements.html <– Generic form elements

    http://framework.zend.com/manual/en/zend.validate.set.html#zend.validate.set.email_address <– Email address validation

    Your tutorial was not advanced, and you're not an advanced php programmer.

    Like

    • Paul,

      I appreciate you taking the time to post a comment. But I really don’t appreciate your assumptions or your tone. This was not meant to be a modular system to re-use through a whole website. This was meant to show different techniques for advanced form validation, aside from any framework type of system. Someone could take parts of the code and implement them into their own system…including zend framework. Personally I prefer to use Drupal, which has a form API. But I’ve used Zend Framework and Code Igniter.

      The term “advanced” is a relative term. You have no idea the projects I’ve worked on, and have no perspective in my experience or my knowledge…other than your interpretation in what this article was meant to do. But honestly my resume speaks for itself. With that said, I do appreciate you bringing up the integrated and reusable systems that someone can use in a system such as Zend Framework.

      Chris Roane

      Like

      • I was basing my comments on a reading of some of the code examples you have on your website. You’re still definitely learning. Don’t get me wrong, so am I, but I’m not the one teaching people poor coding practices on my website.

        In another article you talk about OOP code generally being messy and being an example of something poor in php. I think the opposite. I tend to do absolutely everything with classes in php, and wish the language was oo from the groundup and would fall apart if you didn’t use them (as it happens it pretty much does fall apart if you don’t use objects, but this is not through design – just a result of the awful code that so many people write in php on a day to day basis). I understand you did mention that this applied to people who “don’t know how to write oop properly”, but I’ve seen no classes or objects on this website, which makes me think you don’t know how to use objects properly yourself.

        It took me a while to ‘click’ with objects, and I’m still honing the skills and techiniques. However, I’d say polymorphism has become central to how I work and write my code these days – it’s a beautifully simple techinique and feature of oop code that truly does make your code easier to edit and read. I’ve recently written a report generator, that will allow for reports to be output from my system in absolutely any format I wish (csv, excel file, pdf, json, xml and anything else I want). I can write new reports easily, and they are all instantly convertable to any one of these formats and will work every time. When I write a new report, it’s impossible for the new report to break existing reports, because I’m using polymorphism to segregate all the work properly. I could potentially post some examples for you to see.

        I think it’s good that you’re trying to help people, but you need to step back a bit and not be so over-confident that you actually end up not learning and improving for yourself, never mind other people who may visit your website.

        Like

      • I’ve never said OOP is messy. I’ve said that PHP tends to be messy because it is a loosely typed language and people get lazy.

        I fully understand OOP, but I’m not convinced it is always the best option in PHP. If you’ve worked with C#, you have to do everything using objects and doing something simple is not a quick task (often times).

        I don’t understand why you think that just because I haven’t posted object oriented code that I dont’ know how to use it. Frankly I think it is great to know how to use it and it can save a lot of time if it is implemented right (specifically in a framework system), but you still have to write PHP code in the methods to get things to work. I haven’t really felt the need for writing articles on object oriented programming because my opinion is that this is best done via a larger framework…and I haven’t wrote articles that are specific to code examples using a framework.

        On an interesting note I have been using Drupal for a few years now, and not everything is object oriented (and I’m not using it because I don’t know how to write object oriented code). In fact most things are done through functions. Code is still highly re-used, but it is not done through objects. I just mention this to prove that not everyone has your opinion that everything should be in OO code.

        Since I did not go to college, it took me a while to get a good grasp of OOP (out of the 13 years I’ve done this, it took me a good 3-4 years of general PHP examples to get a firm grip on it). I’ve used it in certain cases and it definitely has made me a better programmer. But I’m not convinced it is always best to use it in every scenario. I’ve gone through stages where everything I used to code in PHP was in objects….but I found that outside of a framework system that is maintained, it wasn’t worth the time putting together. But that is where a system such as Zend Framework comes in.

        Like

      • I read this exchange with sadness. I think Paul’s comments breached an important social etiquette without the usual “IMHO” and passed judgment on a person (you are not an advanced programmer…you are over-confident, etc.) rather than just the work.
        Paul may indeed be a super genius and Chris may indeed be a crackpot, but it does not appear to me that Chris was delivering such poison that Paul had to self-righteously declare himself to be the policeman.
        But the unfortunate way in which Paul’s comments were written was disrespectful and, to me, largely negated his intention in that I was so put off I wondered where he was coming from.
        There is also something worthwhile in Chris taking the time to write this up, and I don’t think Paul, who may or may not have written something in his mind (I am not the one who has written things up on my website), is in a position to take that credit from Chris.
        Bottomline: IMHO (!), I think Paul needs to really step back and not be to over-confident, and if he has something ingenious to say, just say it. Others will read his comments for what they are worth, without having to suffer through his personal judgment.

        Like

  5. Your above validation code could be easily improved by doing what I said above and turning it into an oop validation system. You wouldn’t have to copy/paste code all over the place, and once you’d written the code once it would be portable to any project you wish.

    You could paste this:

    $userInputEmail = $_GET[’email’];

    $emailElement = new EmailElement();

    if (!$emailElement->isValid($userInputEmail)){
    $errors[] = $emailElement->getError();
    }

    And it would work on any website at all.

    Like

    • I agree that this would be a more modular way of doing it. I may implement a standalone form library for this in a future article. Thanks for your comment.

      Like

  6. I was wondering how this would work if one of the form fields is an array, like if the user has to choose her top 2 favorite fruits from a select box?

    Like

  7. Chris, I can’t tell you how helpful this post has been for me. I have been able to adapt some of your concepts to work for my site and do exactly what I need it to do.

    I really appreciate you getting me pointed in the right direction, even if you get criticized for trying to help out. 🙂

    Like

  8. Hi, I’m a beginner, but I understand what you’ve done for the most part. Thanks so much for the post.

    I was wondering what might be required to validate a form based on whether or not a user has submitted the form already by checking if the email address provided has already been submitted?

    I have a basic form with some boolean JS validation plus a regEx email checker, but I need to check their email address too and prevent from submitting more than once.

    Any help or references much appreciated, thanks!

    Like

  9. Great piece here Chris. It is nice to see something piratical in the middle of beginner and advanced. I have been curious about Jquery and how to effectively provide validation in case it goes down. Thanks dude.

    Like

  10. I wrote a form validator in case someone wants to check it out. The approach is slightly different from what is used here. It can be found on jform.lagerwall.net.

    Cheers!

    Like

  11. This example is excellent and assist me well, many thanks. Have you any examples for from validation on login page?

    Like

  12. i like this tutorial. i am asking weather it’s possible to get complete tutorials about validation of website
    .

    Like

  13. Hi, thanks for your great script.
    I need to perform a file upload validation, in other words, only a preset file should be uploaded, if user selects wrong file, notify and let user try again, otherwise, proceed with upload. I’ve tried many scripts, snippets, but neither of them have what I need. Thanks

    Like

  14. How do you add validation for the email format? Like, to make sure it is a real formatted email with the at symbol. How to add to the javascript and the PHP?

    BTW, I used this, tested it with no javascript and it worked. I have to test it with javascript now.

    Also, can you improve this further to add sanitize data for sending to database?

    Thanks for your awesome tutorial.

    Like

  15. This has been very helpful. I am working with just the PHP validation and the only problem that I am having is that when I do the validation and I have a select box or a checkbox my selections are gone and the users have to select their information again or the validation fails when they submit for a second time. Any help would be greatly appreciated.

    Like

  16. Chris thanks very much for all your help, unfortunately great people like you put themselves in the firing line. Paul you need to take a chill pill – you must have crawled out of the wrong side of bed that day! But thank you too for your contribution. Now can’t we all be friends?

    Like

  17. Hi Chris,

    there is a alternative way to avoid loops and iterations over arrays. While you did simply continue after a not allowed field was acknowledged, you should only fetch fields from the array which would be allowed without iterate over all fields. For this job php spends us 2 failsave native methods: array_intersect_key, array_diff_key. Aslong you want emulate register_globals with a part of an array as real variables just extract it and avoid iterate over it ( a seconds, third or more time(s) ).

    http://php.net/array_diff_key
    http://php.net/array_intersect_key
    http://php.net/extract

    For thous people out there who want validation of email-fields and other form-fields which cover floats, integers, bools or a restricted set of characters got a full qualified validator inside of php: filter_var

    http://php.net/filter_var

    an example for validating within array functions and avoiding foreach overall:

    http://codepad.org/8FR9HLTf

    Like

  18. Thanks for the great post… I was able to implement fairly easily. I want to send the data received to a specified email and a copy to the sender, so I added the following code. Is there anything that you would do differently with what I have here? Thanks!

    .error {
    list-style:none;
    background-color:#FAD6DB;
    border:1px solid red;
    padding:5px;
    font-weight:bold;
    )

    $value)
    {
    // first need to make sure this is an allowed field
    if(in_array($key, $allowedFields))
    {
    $$key = $value;

    // is this a required field?
    if(in_array($key, $requiredFields) && $value == ”)
    {
    $errors[] = “The field $key is required.”;
    }
    }
    }

    // were there any errors?
    if(count($errors) > 0)
    {
    $errorString = ‘The following errors were reported.’;
    $errorString .= ”;
    foreach($errors as $error)
    {
    $errorString .= “$error”;
    }
    $errorString .= ”;

    // display the previous form
    include ‘index.php’;
    }
    else
    {
    // At this point you can send out an Email or do whatever you want with the data…

    // each allowed form field Name is now a php variable that you can access

    $Name = $_POST[‘Name’];
    $Email = $_POST[‘Email’];
    $URL = $_POST[‘URL’];
    $Company = $_POST[‘Company’];

    $subject = “Thanks for you inquiry ” . $Name . “”;

    $messageBody = ”
    Thanks for taking the time to fill out our form. Below is a copy of the information you submitted. We will be in touch with you as soon as possible.

    Name: “.$Name.”
    Email: “.$Email.”
    URL: “.$URL.”
    Company: “.$Company.”

    Thank you
    “;

    // send a copy to the lister
    $recipientEmail=$Email;
    $firstLineOfEmail = $subject;
    $messageBody = $firstLineOfEmail . $messageBody;
    $systemEmail = “info@richgraphicdesigns.com “;
    $from = “From: $systemEmailn”; /* used as the 4th mail() argument */
    $replyTo = “Reply-To: $Emailn”;
    $recipient = $recipientEmail;
    $xMailer = “X-Mailer: PHP/” . phpversion();
    $optionalHeaders = $from . $replyTo . $xMailer;
    $customer_Emailed = “NO”;

    if( mail( $recipient, $subject, $messageBody, $optionalHeaders ) ) {
    $customer_Emailed = “YES”;
    }

    $subject = “Sample Form Delivery”;

    $messageBody = ”
    ” . $Name . ” has filled out the International Quote Request on the DCI Website. The information is listed below:

    Name: “.$Name.”
    Email: “.$Email.”
    URL: “.$URL.”
    Company: “.$Company.”
    Thank you,

    Dedicated Carriers Webmaster

    “;

    // Send to Email j

    $recipientEmail= “info@richgraphicdesigns.com”;

    $reg_Emailed = “NO”;

    ini_set(‘sendmail_from’, ‘info@richgraphicdesigns.com’);

    if (mail( $recipientEmail, $subject, $messageBody, $optionalHeaders )){

    $reg_Emailed = “YES”;

    }

    if(($reg_Emailed == “YES”))
    {
    //$msg = ”
    //
    //Thanks for filling out our Quote Request Form
    //Click the X to close this window
    //Dedicated Carriers Inc.
    //”
    ;

    } else {

    $msg = “We are Unable to process your request at this time.
    Please try your again at a later time.
    Thank you for your interest.”;
    }

    //echo “$msg”;

    // display the thank you page
    header(“Location: thanks.html”);
    }
    ?>

    Like

  19. Hi Chris,

    I need help with my php form registration. I want user to be able to review their details before it is finally submitted to the database. After filling all their information, I want user to be presented with all the information that they have supplied and if they are satisfied that the details are correct, then submit the form but if not, return to the form to correct their errors. Please, note that I am not referring to form validation but this is a kind of form summarisation just before submitting the form.

    Your help will be highly appreciated.

    Best regards,
    Sahoong

    Like

    • Help please. in the process.php, i still cannot make it send to my email account, anyone can provide the full code of process.php which can send the email out to email account. thank you very much.

      and i would like to make like http://www.thattechnicalbookstore.com/request.asp
      but still cannot, can anyone can help. i am the beginner of PHP, and never lean before.

      Like

      • I can understand about being a beginner with php. I have worked with this and here is a copy of my process form. I have it doing two different emails – one to the person submitting and one to the person who will process the data. I also have it doing an email validation. Hope this helps.

        ‘Enter the name of the student.’,
        ‘Contact_Name’ => ‘Enter a name for the family contact.’,
        ‘Contact_Phone’ => ‘Enter the phone for the family contact.’,
        ‘Email’ => ‘Email Address is not valid.’,
        ‘Attending’ => ‘Enter the number of people that will be attending.’,
        ‘Friday’ => ‘Select whether you are attending the events on Friday evening.’,
        ‘Learning’ => ‘Select whether you are attending the Fall into Learning Sessions.’,
        ‘Games’ => ‘Select whether you are going to attend the basketball games.’,
        ‘Meals’ => ‘Select whether you are going be eating meals on campus.’,
        ‘Email2’ => ‘Email address entered is not valid.’,
        );

        /*
        * BEGIN FORM VALIDATION
        */

        $errors = array();

        // We need to loop through the required variables to make sure they were posted with the form.

        foreach($requiredFields as $fieldname => $errorMsg)
        {
        if(empty($_POST[$fieldname]))
        {
        $errors[] = $errorMsg;
        }
        }
        if (!preg_match(‘/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/’, $Email2))
        {
        $errors[] = $errorMsg;
        }

        //Validating the email address

        // Loop through the $_POST array, to create the PHP variables from our form.

        foreach($_POST AS $key => $value)
        {
        // Is this an allowed field? This is a security measure.
        if(in_array($key, $allowedFields))
        {
        ${$key} = $value;
        }
        }

        /*
        * END FORM VALIDATION
        */

        // Were there any errors?

        if(count($errors) > 0)
        {
        $errorString = ‘There was an error processing the form.‘;
        $errorString .= ”;
        foreach($errors as $error)
        {
        $errorString .= “$error“;
        }
        $errorString .= ”;
        // display the previous form
        include ‘familyweekendform.php’;

        }
        else
        {

        // At this point you can send out an email
        /* Set e-mail recipient */

        $myemail = “email@email.com”;
        $webemail = “email@email.com”;
        $subject = “Family Weekend”;
        $subject2 = “Family Weekend Confirmation”;
        $header = ‘From: email@email.com‘ . “rn”;

        /* Let’s prepare the autoreply message for the e-mail */

        $message1 =

        “Hello $Contact_Name!

        Thank you for submitting a RSVP for Family Weekend. We look forward to seeing you on
        campus. If you have any further questions, please contact me,

        All the best,

        “;

        /* Let’s prepare the autoreply message for the e-mail */

        /* Let’s prepare the autoreply message for the e-mail */

        $message =

        “Family Weekend contact form:

        Student Name: $Student_Name
        Family Contact Name:: $Contact_Name
        Family Contact Phone Number: $Contact_Phone
        Family Contact Email Address: $Email
        How many people will be attending: $Attending
        Do you plan to attend Friday evening’s actitivies: $Friday
        Do you plan to attend the Fall into Learning Sessions: $Learning
        Do you plan to attend the basketball games:$Games
        Do you plan to eat meals on campus: $meals
        Additional Comments: $Additional_Comments
        “;

        mail($Email, $subject2, $message1, $header);
        mail($myemail, $subject, $message, $header);
        mail($webemail, $subject, $message, $header);

        // display the thank you page

        header(“Location: $thankYouPage”);

        }
        ?>

        Like

Comments are closed.