How to Add Form Validation, Disable Browser Caching and Embed HTML with PHP

PHP Tutorial 2: Improving Your Form to Mail Script


How to Add Form Validation, Disable Browser Caching and Embed HTML with PHP

by Christopher Heng, thesitewizard.com

The first part of my PHP tutorial dealt with the basics of writing a PHP script, and took its readers through the creation of a simple but useful feedback script, which transmits the contents of a feedback form back to the webmaster in an email.

If you missed that article, you can find PHP Tutorial 1: Writing Your First PHP Script: Feedback Form (Email Form) at https://www.thesitewizard.com/archive/feedbackphp.shtml

This article refines that Form to Mail script while at the same time introducing other facilities available in PHP.

Checking / Validating Form Inputs

If you have ever installed a form on your website before, you will probably have received the results of submissions that were incomplete in some way. For example, the visitor submitting the form may have completely omitted his email address. Or, in the case of trigger-happy visitors, they may have accidentally hit the Submit button before even writing their comments.

To make the feedback script more robust, it is useful to have some sort of checking to ensure that all essential fields have been completed before sending the message to the webmaster. The simplest way to do this is to modify the script we wrote in the first part of this tutorial to the following:

<?php
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;

if (!isset($_REQUEST['email'])) {
  header( "Location: http://www.example.com/feedback.html" );
}
elseif (empty($email) || empty($message)) {
  header( "Location: http://www.example.com/error.html" );
}
else {
  mail( "you@example.com", "Feedback Form Results", $message, "From: $email" );
  header( "Location: http://www.example.com/thankyou.html" );
}
?>

If you recall, the feedback form for the purpose of this tutorial is a simple:

<form method="post" action="sendmail.php">
Email: <input type="text" name="email"><br>
Message:<br>
<textarea name="message" rows="15" cols="40"></textarea><br>
<input type="submit">
</form>

Notice that we have inserted several additional checks into our feedback script.

The first change we've made is that we check if the variable $_REQUEST['email'] has been defined by using the isset() function. In the first tutorial, I mentioned that it would have been defined if your script was called from your feedback form since PHP automatically provides your script access to all form fields through $_REQUEST['form-field-name'] (where form-field-name is the name of the field in your form).

This check is useful to catch instances where your visitor tries to invoke "http://www.example.com/sendmail.php" just to see what happens. Without this check, you will end up with a blank email in your mailbox if he/she does this. This revised script checks to see if the "email" field has been set, and if it has not, it means that the visitor has called the script directly without going through your form. In such a case, the script redirects the visitor to your feedback form.

The line

elseif (empty($email) || empty($message))

checks if the form was submitted without the visitor entering anything in either (or both) of those fields. The empty() function checks the variable enclosed within its brackets to see if they contain anything. If nothing is found in either of these variables, or if they have not been set, your visitor will be directed to your error page.

Finally, if all is well, the form is submitted using the code explained in our previous tutorial.

Notice that the script introduces three extra keywords: "if", "elseif" and "else". Like many programming languages, these control structures allow certain portions of your script to be executed only if a particular condition is true. The condition to be tested must be enclosed in the brackets "(" and ")". For example, if you want to the script to print "Hello!" if $email is empty, you can use the following code snippet:

if (empty($email))
  echo "Hello!" ;

Unlike Perl, if the code to be executed is only one statement long (like the "Hello!" example above), you do not need to enclose your code (the echo portion) in curly braces "{" and "}". (I have included the curly braces in the main feedback script above in every instance in order not to confuse you at that early stage.)

Incidentally, the feedback form generated by thesitewizard.com's Feedback Form (Email Form) Wizard contains all the above enhancements (and more). If you want to examine the production code for an email form, just use it to create a form and script. There is also a demo page for the script the wizard produces, so you can try it out to see how it works.

Generating HTML Code

It is possible to make your PHP script generate HTML code instead of simply redirecting the visitor's browser to a separate HTML file.

For example, if you prefer to generate your error message directly from the sendmail.php script above, you might wish to modify the script as follows:

<?php
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;

if (!isset($_REQUEST['email'])) {
  header( "Location: http://www.example.com/feedback.html" );
}
elseif (empty($email) || empty($message)) {
  ?>

  <html>
  <head><title>Error</title></head>
  <body>
  <h1>Error</h1>
  <p>
  Oops, it appears you forgot to enter either your
  email address or your message. Please press the BACK
  button in your browser and try again.
  </p>
  </body>
  </html>

  <?php
}
else {
  mail( "you@example.com", "Feedback Form Results", $message, "From: $email" );
  header( "Location: http://www.example.com/thankyou.html" );
}
?>

As you can see from the example, it is trivial to make PHP generate HTML code. Simply close off the script with the "?>" and PHP will send all text to the web server unmodified until it encounters another "<?php".

Preventing the Browser From Caching

If you generate HTML code from your PHP script, you should probably also mark the generated code as something that your visitor's browser should not cache. Otherwise, the next time the visitor invokes "sendmail.php" directly, he/she might see your error page instead of being redirected to your feedback form.

To invalidate the cache in your visitor's browser, modify the above script as follows:

[...preceding code...]

elseif (empty($email) || empty($message)) {

  header( "Expires: Mon, 20 Dec 1998 01:00:00 GMT" );
  header( "Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT" );
  header( "Cache-Control: no-cache, must-revalidate" );
  header( "Pragma: no-cache" );

  ?>

  <html>
  <head><title>Error</title></head>
  <body>
  <h1>Error</h1>
  <p>
  Oops, it appears you forgot to enter either your
  email address or your message. Please press the BACK
  button in your browser and try again.
  </p>
  </body>
  </html>

  <?php

[...etc...]

The PHP script outputs some HTTP headers to the browser in an attempt to force browsers and proxies not to cache the page. Since there isn't a common HTTP header that will work with every single browser and proxy out there, the script tries to cover as many bases as it can by issuing a variety of headers.

Remember that all HTTP headers must be sent to the browser before any HTML code is generated. As such, if your script needs to issue HTTP headers (using the header function), make sure that you start the script with "<?php" and only generate HTML code after any HTTP headers have been sent. If your script starts with HTML code you will not be able to use the header function without receiving an error.

Adding Additional Fields

As it stands (subject to your writing the various HTML files like feedback.html, thankyou.html, error.html or embedding the HTML code in the script itself) the script can already be used on your website.

If you like, you might want to improve the script and feedback form in the following ways:

  1. Add support for your visitor's name. Otherwise when you reply, you would not be able to address him or her by name. You will of course need to code your script so that it includes those fields. For example, if your name field is called "name", you might want to modify your call to the mail function as follows:

    $name = $_REQUEST['name'] ;
    mail( "you@example.com", "Feedback Form Results", $message, "From: $name <$email>" );
  2. Likewise if you include other fields like: "How did you hear of this website?", you might want to encode the results as in the following example. Here I assume that the answer is given in the field named "whosentyou".

    $whosentyou = $_REQUEST['whosentyou'] ;
    mail( "you@example.com", "Feedback Form Results",
      "$message\nHow did you hear of this website? $whosentyou\n",
      "From: $name <$email>" );

    The "\n" inserts a new line character into the message, causing the line "How did you hear of this website? (etc)" to begin on a new line.

  3. Improve the formatting on the feedback form itself. Put it in a table, or use Cascading Style Sheets, to align the various form elements; expand the size of the various input boxes, or otherwise beautify the appearance of the form. It currently looks quite ugly, although functional. This is however beyond the scope of this PHP tutorial.

Embedding the Feedback Form into the PHP Script

It is possible to make your PHP script, sendmail.php, serve both as the form web page, the email sending script (which is what it is now), as well as the "Thank You" page. The visitor who loads sendmail.php will immediately see your feedback form, and "sendmail.php" will appear in his browser's location bar. After he sends his feedback, he receives the "Thank You" page, but the address bar in his browser still shows "sendmail.php".

This is trivial to implement. Taking the script we developed above, we simply change the initial lines to the following to do this.

<?php
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;

if (!isset($_REQUEST['email'])) {
  ?>

  <html>
  <head><title>Feedback Form</title></head>
  <body>
  <h1>Feedback Form</h1>
  <p>
  <form method="post" action="sendmail.php">
  Email: <input type="text" name="email"><br>
  Message:<br>
  <textarea name="message" rows="15" cols="40"></textarea><br>
  <input type="submit">
  </form>
  </p>
  </body>
  </html>

  <?php
}

[...etc...]

With these changes, your feedback form will look like it is submitting the form to itself. Your visitors will, however, not be able to see the script itself, only the HTML code for the feedback form.

The Next Step

At this point, you not only have a functional and useful feedback form, you also have the skills and knowledge to extend and customise the script to suit your purposes for your website. As you can see, programming with PHP is actually extremely easy — the language is intuitive and has many built-in facilities for the web programmer.

You should now proceed to the chapter on How to Prevent Email Injection in Your PHP Form to Mail Scripts to learn how to protect your script from being exploited by spammers to send spam.

Copyright 2000-2017 by Christopher Heng. All rights reserved.
Get more free tips and articles like this, on web design, promotion, revenue and scripting, from https://www.thesitewizard.com/

This article can be found at https://www.thesitewizard.com/archive/phptutorial2.shtml

thesitewizard™ News Feed (RSS Site Feed)  Subscribe to thesitewizard.com newsfeed

Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at https://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.

Please Do Not Reprint This Article

This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form.

Related Pages

New Articles

How to Link to This Page

It will appear on your page as:

How to Add Form Validation, Disable Browser Caching and Embed HTML with PHP





Home
Donate
Contact
Link to Us
Topics
Site Map

Getting Started
Web Design
Search Engines
Revenue Making
Domains
Web Hosting
Blogging
JavaScripts
PHP
Perl / CGI
HTML
CSS
.htaccess / Apache
Newsletters
General
Seasonal
Reviews
FAQs
Wizards

 

 
Free webmasters and programmers resources, scripts and tutorials
 
HowtoHaven.com: Free How-To Guides
 
Site Design Tips at thesitewizard.com
Find this site useful?
Please link to us.