Friday, March 29, 2024

PHP Tutorial: Error Handling

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:

<html>
<head>
<title>Process Uploaded File</title>
</head>
<body>
<?php

move_uploaded_file ($_FILES[’uploadFile’] [’tmp_name’],
       "../uploads/{$_FILES[’uploadFile’] [’name’]}")

?>
</body>
</html>
 

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 <form>:

<input type="hidden" name="MAX_FILE_SIZE" value="25000" />

I’m showing a maximum size of 25,000 bytes here, but you can use any size you
wish.

Now to handle those errors!  PHP is not going to leave us high and dry. 
Instead, it includes some very helpful features.

First, we need to know if our file upload was successful or if any error
occurred.  Happily, we can test the result of the move_uploaded_file
function directly.  If it was successful, it will return "true", if any
error occurred, it will return "false", which enable us to test it with an "if"
statement like this:

if ( move_uploaded_file ($_FILES[’uploadFile’] [’tmp_name’],
       "../uploads/{$_FILES[’uploadFile’] [’name’]}")  )
      {  print ‘<p> The file has been successfully
uploaded </p>’;
       }
else
      {   // error handling code goes here
       }

In this example, I’ve left out the actual error handling code for the moment
so that you can clearly see how the "if" tests the true/false return from the
move_uploaded_file function.

Now we need to find out what kind of error occurred and do something about
it.  You will remember from the
last part of this series that
we discussed the $_FILES array and is associative indexes.  There is anothe
such index called ‘error’ that returns a value to indicate what kind of error
has occurred. We can conveniently test this value by using a "switch…. 
case" construct.

A "switch….  case" construct is like coding a series of "if…. else"
statements, except that it is much tidier and easier to read.  Basically
the "switch" part specifies a variable to be tested for a series of values, and
the "case" parts say what to do in "case the value is this".  This is what
it looks like when it is applied to our example:

switch ($_FILES[’uploadFile’] [’error’])
 {  case 1:
           print ‘<p> The file
is bigger than this PHP installation allows</p>’;
           break;
    case 2:
           print ‘<p> The file
is bigger than this form allows</p>’;
           break;
    case 3:
           print ‘<p> Only
part of the file was uploaded</p>’;
           break;
    case 4:
           print ‘<p> No file
was uploaded</p>’;
           break;
 }

We now have code to handle the error situation we discussed earlier! 
Putting it all together, we get the following code (showing first the form, then
the PHP page that handles the form):

<html>
<head>
<title>File Upload Form</title>
</head>
<body>
This form allows you to upload a file to the server.<br>

<form action="getfile.php" method="post"><br>
Type (or select) Filename: <input type="file" name="uploadFile">
<input type="hidden" name="MAX_FILE_SIZE" value="25000" />
<input type="submit" value="Upload File">
</form>

</body>
</html>

and now the PHP page to handle the form:

<html>
<head>
<title>Process Uploaded File</title>
</head>
<body>
<?php

if ( move_uploaded_file ($_FILES[’uploadFile’] [’tmp_name’],
       "../uploads/{$_FILES[’uploadFile’] [’name’]}")  )
      {  print ‘<p> The file has been successfully
uploaded </p>’;
       }
else
      {
        switch ($_FILES[’uploadFile’]
[’error’])
         {  case 1:
                  
print ‘<p> The file is bigger than this PHP installation allows</p>’;
                  
break;
            case 2:
                  
print ‘<p> The file is bigger than this form allows</p>’;
                  
break;
            case 3:
                  
print ‘<p> Only part of the file was uploaded</p>’;
                  
break;
            case 4:
                  
print ‘<p> No file was uploaded</p>’;
                  
break;
         }
       }

?>
</body>
</html>
 

We now have a much more elegant file upload process!

 

Continue to the next part of this Tutorial


Return to the Tutorial Series Index

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured