Page 302 - Beginning PHP 5.3
P. 302
Part III: Using PHP in Practice
case UPLOAD_ERR_NO_FILE:
$message = “No file was uploaded. Make sure you choose a file to
upload.”;
break;
default:
$message = “Please contact your server administrator for help.”;
}
echo “ < p > Sorry, there was a problem uploading that photo. $message < /p > ”;
}
The displayForm() function simply displays the file upload form, with a text field for the visitor ’ s
name and a file select field to allow a file to be uploaded. Finally, the displayThanks() function
thanks the user, displaying the user ’ s name (if supplied) and his photo.
Redirecting after a Form Submission
Before leaving the topic of form handling in PHP, it ’ s worth mentioning the concept of URL redirection.
Though not directly related to forms, URL redirection is often used within form handling code.
Normally when you run a PHP script — whether by typing its URL, following a link, or submitting a
form — the script does its thing, displays some sort of response as a Web page, and exits.
However, by sending a special HTTP header back to the browser from the PHP script, you can cause the
browser to jump to a new URL after the script has run. This is commonly used within a form handler
script to redirect the users to a thank - you page after they ’ ve submitted the form. This means that you can
keep your thank - you page separate from your PHP script, which makes the page easier to edit and
update.
Another good thing about redirecting to a new URL after a form has been submitted is that it prevents
users from accidentally resubmitting the form by clicking their browser ’ s Reload or Refresh button.
Instead, all that happens is that they reload the page that they were redirected to.
Redirection is as simple as outputting a Location: HTTP header, including the URL you want to
redirect to. You output HTTP headers in PHP using the built - in header() function. So here ’ s how
to redirect to a page called thanks.html :
header( “Location: thanks.html” );
The only thing to watch out for is that you don ’ t output any content to the browser — whether via
echo() or print() , or by including HTML markup outside the < ?php ... ?> tags — before calling
header() . This is because the moment you send content to the browser, the PHP engine automatically
sends the default HTTP headers — which won ’ t include your Location: header — and you can send
headers only once per request.
264
9/21/09 7:23:50 PM
c09.indd 264
c09.indd 264 9/21/09 7:23:50 PM