It is the mark of a good programmer that they do not stop once they have
found a way to make something work. Instead, the conscientious programmer
sets about finding every way that their solution might not work, and then writes
some code to cover those situations. Quality program code handles all
foreseeable error situations, gracefully informing the user of the error that
has occurred, and not just crashing, going away and leaving the user’s mouth
hanging open having just said "wha’….???"
This type of code is known as Error Handling, and we’re going to apply some
to the file upload solution we
just created. This was our "getfile.php" page:
move_uploaded_file ($_FILES[’uploadFile’] [’tmp_name’],
"../uploads/{$_FILES[’uploadFile’] [’name’]}")
?>
Now we have to think of the kinds of error situations that might occur.
The first, and perhaps the most obvious, is that something goes wrong in the
middle of the file transfer, and only a part of the file makes it through.
It is also possible that for some reason (perhaps to do with the user’s file
selection, or permissions or any other such reason) no file was uploaded at all.
There are also some possible errors that could arise because of capabilities
in PHP itself. PHP can be configured on the server to only allow file
transfers of files up to a certain size. When this size is exceeded, an
error occurs. We can also set a file size limit ourselves by adding a
MAX_FILE_SIZE limit to our HTML form. To do this, we would add a line like
this one inside our
and now the PHP page to handle the form:
if ( move_uploaded_file ($_FILES[’uploadFile’] [’tmp_name’],
"../uploads/{$_FILES[’uploadFile’] [’name’]}") )
{ print ‘
The file has been successfully
uploaded
}
else
{
switch ($_FILES[’uploadFile’]
[’error’])
{ case 1:
print ‘
The file is bigger than this PHP installation allows
’;break;
case 2:
print ‘
The file is bigger than this form allows
’;break;
case 3:
print ‘
Only part of the file was uploaded
’;break;
case 4:
print ‘
No file was uploaded
’;break;
}
}
?>
We now have a much more elegant file upload process!
Continue to the next part of this Tutorial
Return to the Tutorial Series Index