Page 301 - Beginning PHP 5.3
P. 301
Chapter 9: Handling HTML Forms with PHP
How It Works
The script first checks to see if the form has been submitted by looking for the existence of the
sendPhoto submit button field. If the form was submitted, processForm() is called to handle the
form; otherwise the form is displayed with displayForm():
if ( isset( $_POST[“sendPhoto”] ) ) {
processForm();
} else {
displayForm();
}
processForm() handles the uploaded file (if any). First it checks to make sure a file was uploaded,
and that it uploaded without error:
if ( isset( $_FILES[“photo”] ) and $_FILES[“photo”][“error”] == UPLOAD_
ERR_OK ) {
If the uploaded file is not a JPEG photo, the function refuses it:
if ( $_FILES[“photo”][“type”] != “image/jpeg” ) {
echo “ < p > JPEG photos only, thanks! < /p > ”;
The function then attempts to move the uploaded file from the temporary folder to the photos folder,
displaying an error message if there was a problem. If all goes well, the thank - you page is displayed:
} elseif ( !move_uploaded_file( $_FILES[“photo”][“tmp_name”], “photos/” .
basename( $_FILES[“photo”][“name”] ) ) ) {
echo “ < p > Sorry, there was a problem uploading that photo. < /p > ”;
} else {
displayThanks();
}
Note the use of the PHP basename() function. This takes a file path and extracts just the filename
portion of the path. Some browsers send the full path of the file when it ’ s uploaded — not just the
filename — so the script uses basename() to make sure that only the filename portion is used for the
file in the photos folder. Furthermore, this prevents attackers from inserting malicious characters (for
example, “../” ) into the filename.
The function also displays an error message if no photo was uploaded, or if PHP reported an error in
the $_FILES array:
} else {
switch( $_FILES[“photo”][“error”] ) {
case UPLOAD_ERR_INI_SIZE:
$message = “The photo is larger than the server allows.”;
break;
case UPLOAD_ERR_FORM_SIZE:
$message = “The photo is larger than the script allows.”;
break;
263
9/21/09 7:23:50 PM
c09.indd 263
c09.indd 263 9/21/09 7:23:50 PM