Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

PHP 5 Recipes A Problem-Solution Approach 2005 phần 9 ppsx
Nội dung xem thử
Mô tả chi tiết
Selection:
<select name="myselection">
<option value="nogo">make a selection...</option>
<option value="1"<?php if ($_POST['myselection'] == 1){?>➥
selected="selected"<?php } ?>>Choice 1</option>
<option value="2"<?php if ($_POST['myselection'] == 2){?>➥
selected="selected"<?php } ?>>Choice 2</option>
<option value="3"<?php if ($_POST['myselection'] == 3){?>➥
selected="selected"<?php } ?>>Choice 3</option>
</select><br /><br />
Your Email: <input type="text" name="youremail" maxlength="150"➥
value="<?php echo $_POST['youremail']; ?>" /><br />
<input type="submit" value="Submit" style="margin-top: 10px;" />
</form>
<?php
}
?>
</div>
</body>
</html>
Figure 13-1 shows the potential output if you input a valid name field but leave the selection and e-mail address empty.
Figure 13-1. Telling users to properly enter information
How It Works
In this example, you have seen how you may want to handle your validation. Keep in mind
that your objective is to ensure that users know what they did wrong and keep their properly
submitted information for ease of use. To ensure that the user of this form sees the error messages, the Cascading Style Sheet (CSS) class called error will be used every time an error
message is displayed. The error message will display in bold and red, thus directing the users
to realize what they did wrong.
By providing the value fields, and in the case of the select box a selected argument if you
have valid data, the form fields will retain any current, proper information. If there is no current, proper data to use, nothing will display. This form has now become decidedly easy to
use, is quite secure, and ensures a happy, well-directed user.
498 13-5 ■ REDISPLAYING FORMS WITH PRESERVED INFORMATION AND ERROR MESSAGES
5092_Ch13_FINAL 8/26/05 9:58 AM Page 498
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.
13-6. Preventing Multiple Submissions on the Server Side
You can deal with multiple submittal validation in essentially 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 (and explained in the next example). Because the server has no actual
access to the browser, validating multiple submissions can be a bit trickier. While you can
accomplish this goal in a number of ways from a server-side perspective, we prefer to use a
session-based method. Basically, once the submit button has been clicked, the server logs the
request from the individual user. If the user attempts to resubmit a request, the script notes a
request is already in motion from this user and denies the subsequent request. Once the script
has finished processing, the session is unset, and you have no more worries.
For the following example, you will need a test.txt text file that you can create and place
relative to the script. (Or you can ensure that you have write privileges on the working directory, and the script will attempt to create it for you.) Keep in mind that the file must have the
proper privileges set for writing (CHMOD to 777 to keep things simple).
The Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"➥
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Sample 13.6</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<div style="width: 500px; text-align: left;">
<form action="sample13_6_process.php" method="post">
<p>Example:</p>
<input type="hidden" name="submitted" value="yes" />
Your Name: <input type="text" name="yourname" maxlength="150” /><br />
<input type="submit" value="Submit" style="margin-top: 10px;" />
</form>
</div>
</body>
</html>
<?php
//Start the session state.
session_start ();
13-6 ■ PREVENTING MULTIPLE SUBMISSIONS ON THE SERVER SIDE 499
5092_Ch13_FINAL 8/26/05 9:58 AM Page 499
//Set a session started value for this user.
if (!isset ($_SESSION['processing'])){
$_SESSION['processing'] = false;
}
//Now you ensure you haven't already started processing the request.
if ($_SESSION['processing'] == false){
//Now, you let the script know that you are processing.
$_SESSION['processing'] = true;
//Create a loop that shows the effect of some heavy processing.
for ($i = 0; $i < 2000000; $i++){
//Thinking...
}
//Every time you do this, write to a text file so you can test that
//the script isn't getting hit with multiple submissions.
if ($file = fopen ("test.txt","w+")){
fwrite ($file, "Processing");
} else {
echo "Error opening file.";
}
//Then you start doing the calculations.
echo $_POST['yourname'];
//Then, once you have finished calculating, you can kill the session.
unset ($_SESSION['processing']);
}
?>
How It Works
Now, enter your name and continue to jam on the submit button. Rather than allow the script
to continually run time and time again, the script verifies your existence via a session and determines if it is already processing your server call. If the script sees you are already processing,
then it will not allow you to try again no matter how many times you click the same button.
Once the script has finished performing its action, it merely unsets the session variable, and you
could theoretically start again. By checking the session, the script ensures that it is the same user
attempting to access the script and can therefore block multiple attempts from the same user.
13-7. 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. With well-placed JavaScript, you can ensure that the browser will
not let the submittal go through more than once. The problem with this method, of course,
is that JavaScript is not always foolproof because of the user’s ability to turn it off. That being
said, however, most users will have JavaScript enabled, so this script will likely work for
500 13-7 ■ PREVENTING MULTIPLE SUBMISSIONS ON THE CLIENT SIDE
5092_Ch13_FINAL 8/26/05 9:58 AM Page 500
90 percent of web users. The following example uses JavaScript to cut off multiple submittals
from a client-side (browser) level.
Don’t forget to ensure that you have a valid test.txt file (CHMOD to 777), as specified in the
previous recipe.
The Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"➥
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Sample 13.7</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script language="javascript" type="text/javascript">
<!--
function checkandsubmit() {
//Disable the submit button.
document.test.submitbut.disabled = true;
//Then submit the form.
document.test.submit();
}
//-->
</script>
</head>
<body>
<div style="width: 500px; text-align: left;">
<form action="sample13_6_process.php" method="post" name="test"➥
onsubmit="return checkandsubmit ()">
<p>Example:</p>
<input type="hidden" name="submitted" value="yes" />
Your Name: <input type="text" name="yourname" maxlength="150" /><br />
<input type="submit" value="Submit" style="margin-top: 10px;"➥
id="submitbut" name"submitbut" />
</form>
</div>
</body>
</html>
<?php
//Create a loop that shows the effect of some heavy processing.
for ($i = 0; $i < 2000000; $i++){
//Thinking...
}
//Every time you do this, let's write to a text file so you can test that
//out script isn't getting hit with multiple submissions.
if ($file = fopen ("test.txt","w+")){
fwrite ($file, "Processing");
} else {
13-7 ■ PREVENTING MULTIPLE SUBMISSIONS ON THE CLIENT SIDE 501
5092_Ch13_FINAL 8/26/05 9:58 AM Page 501
echo "Error opening file.";
}
//Then you start doing the calculations.
echo $_POST['yourname'];
?>
How It Works
We realize that this particular piece of functionality is based on JavaScript and this is a book
about PHP, but PHP is a server-side language. Therefore, to do a little client-side validation,
you must use a language that can interact with the browser, such as JavaScript. In any case,
the way this script works is by actually disabling the submit button once the form has been
submitted. The button is clicked, which forces the browser to redirect first to the JavaScript
function checkandsubmit(), which immediately disables the submit button and then submits
the form for you. At this point, it does not matter how long the script takes to finish executing;
the submit button is disabled and hence cannot be clicked again until the page is revisited.
13-8. 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. The following example allows you to upload an image (of the file type JPG
only) that is smaller than 500KB in size.
Keep in mind that in order for this script to work, you must have a directory created (relative to the script) that is called uploads and is writable (again, using a CHMOD of 777 is the
simplest way of accomplishing this).
The Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"➥
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Sample 13.8</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<div style="width: 500px; text-align: left;">
<?php
//If you have received a submission.
if ($_POST['submitted'] == "yes"){
$goodtogo = true;
//Check for a blank submission.
502 13-8 ■ PERFORMING FILE UPLOADS
5092_Ch13_FINAL 8/26/05 9:58 AM Page 502