Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

PREVENTING MULTIPLE SUBMISSIONS OF A FORM

One possible occurrence that happens often is that users become impatient when waiting for your
script to do what it is doing, and hence they click the submit button on a form repeatedly. This
can wreak havoc on your script because, while the user may not see anything happening, your
script is probably going ahead with whatever it has been programmed to do. Of particular danger
are credit card number submittals. If a user continually hits the submit button on a credit card
submittal form, their card may be charged multiple times if the developer has not taken the time
to validate against such an eventuality.

1. Preventing Multiple Submissions on the Server Side:


Multiple submittal validation in essentially occur in two ways.
 The first occurs on the server. Server side refers to a script located on the server that is
receiving the data;
 client side is more browser related.

For the following example, consider a test.txt text file that you can create and place relative to
the script.

2. Preventing Multiple Submissions on the Client Side:


Handling multiple submittals from a client-side perspective is actually much simpler than doing
it on the server side. The following example uses JavaScript to cut off multiple submittals from a
client-side (browser) level.

3. Performing File Uploads:

Handling file uploads in PHP is not exactly difficult from a syntax point of view, but it is
important (extremely important in fact) to ensure that the file being uploaded is within the upload
constraints you lay out for it. In other words, an individual user could easily upload a virus or
some other form of malicious software if you are not careful about allowing them to upload only
what you want from them. A similar consideration is file size. You could easily find your server
under some heavy loads if you are not careful about what size of files are being uploaded.
$_FILES Arguments are as follows
As for moving the actual file and saving it, use two methods for performing this action. The two
functions in PHP that will allow to save a file are the copy() and move_uploaded_file()
functions. Use the move_uploaded_file() function, as it will work even when PHP’s safe mode is
enabled. If PHP has its safe mode enabled, the copy() function will fail. They both work largely
the same, so there is no real downside to using the move_uploaded_file() function over the
copy() function.

4. Handling Special Characters:


An added security feature, particularly when dealing with database submittal, is validating
against special characters being inserted into the script. Be it a database insertion script, a contact
form, or even a mailer system, you always want to ensure that no malicious users are attempting
to sabotage your script with bad (or special) characters. PHP allots a number of functions to use
in this regard. In the following example, you will look at the functions trim(), htmlspecialchars(),
strip_tags(), and addslashes(). Their prototypes are as follows:
string trim ( string str [, string charlist] )
string htmlspecialchars ( string string [, int quote_style [, string charset]] )
string strip_tags ( string str [, string allowable_tags] )
string addslashes ( string str )
5. Creating Form Elements with Multiple Options:
From time to time, it will occur to you as a developer that you may need to retrieve several
values from the same select box. Luckily, HTML and PHP 5 have made an allowance for such a
feature. Commonly referred to as a list box, the functionality involved allows you to select a
multitude of items (by holding down the Control key) and then submit them as one. The
following example allows you to select a number of items and then display only the selected
items in the script

6. Creating Form Elements Based on the Current Time and/or Date


Occasionally, it makes sense to create a form-based element that will react according to the
current date and/or time on the server. Doing so speeds up form entry for the user and can make
things slightly more ergonomic. To create this sort of functionality, you merely embed
some PHP into the HTML to create a dynamic element set. The following example allows you to
select a value with the form elements being preset to the current date and time.
Preventing multiple PHP form submissions
When submitting a HTML form it can take several seconds before the form is successfully
submitted and the response page shown. People can get inpatient and click the Submit button
several times which can result in duplicate form submissions. Usually it's not really a problem,
but in some cases you might want to prevent this from happening.

Below you will find two simple tricks for preventing duplicate submissions, you can use either of
these or a combination of both.

prevent multiple form submissions using Javascript

Using Javascript to block duplicate submissions is probably the easiest way. When someone
submits the form we simply disable the Submit button and maybe change it's value to something
more descriptive, like "Submitting, please wait..."

Try clicking this button for example. It will remain disabled until you reload this page:

The first step is to give your submit button a unique id, for example id="myButton":

<input type="submit" value="Submit" id="myButton" />

The second (and last) step is to give two Javascript commands to the <form> tag. The first one
will tell the browser to disable the submit button after the form has been submitted and the
second one will change the button text to give the user some idea about what's happening. This is
the code to add to your form tag:

onsubmit="document.getElementById('myButton').disabled=true;
document.getElementById('myButton').value='Submitting, please wait...';"

Your form tag would then look something like:

<form action="contact.php" method="post"


onsubmit="document.getElementById('myButton').disabled=true;
document.getElementById('myButton').value='Submitting, please wait...';"
>

That's it. This trick should work in most modern browsers (IE 5+, FireFox, Opera, ...).

» prevent multiple form submissions using cookies

If you wish to avoid duplicate submissions for the entire browser session (or longer) you can
consider using cookies. For example edit your form processing script to send a cookie to the
browser after the form has been processed but before any HTML or redirection headers are
printed. Placing this code after the mail() command should work in most cases:
setcookie('FormSubmitted', '1');

Then check for the cookie before processing. If it's there this visitor already submitted the form
in active browser session. Add this code to the beginning of your form processing script:

if (isset($_COOKIE['FormSubmitted']))
{
die('You may only submit this form once per session!');
}

That's it!

» Simple contact form

<html>
<body>
<form action="myform.php" method="post">
<p>Your Name: <input type="text" name="yourname" /><br />
E-mail: <input type="text" name="email" /></p>

<p>Do you like this website?


<input type="radio" name="likeit" value="Yes" checked="checked" /> Yes
<input type="radio" name="likeit" value="No" /> No
<input type="radio" name="likeit" value="Not sure" /> Not sure</p>

<p>Your comments:<br />


<textarea name="comments" rows="10" cols="40"></textarea></p>

<p><input type="submit" value="Send it!"></p>


</form>
</body>
</html>

See the example HTML code above? This is a simple HTML form with two input fields, one
radio box group and a text area for comments. Let's say we save this code in a file called
"test.html". When submitted data is sent to the "myform.php" file using POST HTTP method.

All variables passed to the current script via the HTTP POST method are stored in associative
array $_POST. In other words, in PHP you can access data from each field using
$_POST['NAME'], where NAME is the actual field name. If you submit the form above you
would have access to a number of $_POST array values inside the myform.php file:

Variable Holds value of


$_POST['yourname'] text field "yourname"
$_POST['email'] text field "email"
$_POST['likeit'] selected radio box group "likeit"
$_POST['comments'] textarea "comments"
With register_globals activated all form data is automatically stored in variable $name (where
name is field name, for example $yourname or $email), but this can lead to various security
issues and should be avoided at all cost! This feature is now officially depreciated and disabled
by default.

Now, if you wanted to display submitted data you could simply echo all the variables as shown
below, but do not! Why? Read further.

<html>
<body>
Your name is: <?php echo $_POST['yourname']; ?><br />
Your e-mail: <?php echo $_POST['email']; ?><br />
<br />
Do you like this website? <?php echo $_POST['likeit']; ?><br />
<br />
Comments:<br />
<?php echo $_POST['comments']; ?>
</body>
</html>

If you saved this code in a file called "myform.php", filled the fields in the test.html form and hit
the Submit button, the myform.php output would look something like this:

Your name is: John Doe


Your email: john@doe.com
Do you like this website? Yes
Comments:
This is my comment...

Quite simple, isn't it? But the most important thing is still missing! You need to validate
submitted data to protect your script (and thus your website and server) from malicious code.

Let's say you display all data submitted with the form in a HTML file (like a guestbook does for
example). Now consider someone types this code instead of his name:

<script>location.href('http://www.SPAM.com')</script>

If this is stored in a HTML file anyone who tried to view it would be redirected to
http://www.SPAM.com! And this is the least that can happen! Failure to properly validate input
data is the main reason for most vulnerabilities and exploits in PHP scripts. You wouldn't want
someone to hack your website, erase all data and upload his/her own "u \/\/3R3 H4><0r3d!"
homepage, would you?

Read this tutorial further to learn how to validate form inputs and protect yourself from exploits.

<?php
/* Prevent duplicate submissions */
if (isset($_COOKIE['FormSubmitted']))
{
show_error('You may only submit this form once per session!');
}

/* Set e-mail recipient */


$myemail = "you@domain.com";

/* Check all form inputs using check_input function */


$yourname = check_input($_POST['yourname'], "Enter your name");
$subject = check_input($_POST['subject'], "Write a subject");
$email = check_input($_POST['email']);
$website = check_input($_POST['website']);
$likeit = check_input($_POST['likeit']);
$how_find = check_input($_POST['how']);
$comments = check_input($_POST['comments'], "Write your comments");

/* If e-mail is not valid show error message */


if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}

/* If URL is not valid set $website to empty */


if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $website))
{
$website = '';
}

/* Let's prepare the message for the e-mail */


$message = "Hello!

Your contact form has been submitted by:

Name: $yourname
E-mail: $email
URL: $website

Like the website? $likeit


How did he/she find it? $how_find

Comments:
$comments

End of message
";

/* Send the message using mail() function */


mail($myemail, $subject, $message);

/* Set a cookie to prevent duplicate submissions */


setcookie('FormSubmitted', '1');

/* Redirect visitor to the thank you page */


header('Location: thanks.htm');
exit();

/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}

function show_error($myError)
{
?>
<html>
<body>

<b>Please correct the following error:</b><br />


<?php echo $myError; ?>

</body>
</html>
<?php
exit();
}
?>

You might also like