Creating an Error Handling Module for a PHP 5 File Uploader

Welcome to the third chapter of the series “Building file uploaders with PHP 5.” Comprised of five approachable tutorials, this series teaches you the fundamentals of constructing file uploading applications with PHP 5. It also complements the corresponding theoretical concepts with numerous hands-on examples. In this third tutorial of the series, I’m going to show you how to incorporate a brand new error checking module into the file uploading PHP script created in the last article.

As with many other topics related to the development of modern web applications, PHP makes file uploading a no-brainer process, even for those programmers who are just starting to familiarize themselves with the basics of this popular language. Fortunately, the intrinsic flexibility of PHP permits us to build file uploading applications using a procedural approach and the object-oriented paradigm. Thus, if you’re interested in learning how to implement file uploads by way of a few simple functions and classes, then don’t waste more time and start reading this article series now!

Now that you’re familiar with the goal of this article series, I’d like to spend a few moments rehashing the topics that were treated in the last article, in case you haven’t the chance to read it. In simple terms, I explained how to build a rudimentary file uploading application that was given the ability to display useful information about an uploaded file, including its MIME type and size expressed in bytes, and its temporary name and client names as well.

This capacity was introduced into the script in question via the $_FILES super global array, which provides detailed information on each file uploading process performed with PHP. However, it’s fair to highlight an important point regarding the use of this array: it also includes a handy element that stores different error codes when a file has been uploaded to the web server. As you may have guessed, it’s possible to use this set of error numbers to implement an efficient error handling module that keeps track of the different failures that might occur during a specific file upload.

It’s time to dispose of the preliminaries and learn how to create the aforementioned error processing module in a few easy steps. Let’s go!

{mospagebreak title=Performing file uploads without checking errors}

If you’re anything like me, then you’ll feel curious about how to include an effective error checking mechanism inside the file uploading script that I built in the preceding article of this series. Thus, let me quickly show you the complete source code of this application, including the corresponding web form that permits users to browse files in their respective client machines.

Here are the source files that comprise the file uploading application:


(definition of ‘upload_form.htm’ file)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Uploading files with PHP</title>

<style type="text/css">

body{

padding: 0;

margin: 0;

background: #fff;

}

h1{

font: bold 16pt Arial, Helvetica, sans-serif;

color: #000;

text-align: center;

}

p{

font: normal 10pt Arial, Helvetica, sans-serif;

color: #000;

}

form{

display: inline;

}

#formcontainer{

width: 50%;

padding: 10px;

margin-left: auto;

margin-right: auto;

background: #eee;

border: 1px solid #666;

}

</style>

</head>

<body>

<h1>Uploading files with PHP</h1>

<div id="formcontainer">

<form enctype="multipart/form-data" action="upload_file.php" method="post">

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

<p>File to upload <input name="userfile" type="file" />

<input type="submit" name="send" value="Upload File" /></p>

</form>

</div>

</body>

</html>



(definition of ‘upload_file.php’ file)

 

if($_POST['send']){

// set upload directory (for Windows users)

$uploadDir=’C:uploaded_files';

// set destination of uploaded file

$uploadFile=$uploadDir.basename($_FILES['userfile']['name']);

if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadFile)){

echo ‘The target file was successfully uploaded!<br />';

echo ‘Name of uploaded file: ‘.$_FILES['userfile']['name'].’.<br />';

echo ‘MIME type of uploaded file: ‘.$_FILES['userfile']['type'].’.<br />';

echo ‘Size of uploaded file: ‘.$_FILES['userfile']['size'].’ bytes.<br />';

echo ‘Temporary name of uploaded file: ‘.$_FILES['userfile']['tmp_name'].'<br />';

}

else{

echo ‘Error uploading target file!';

}

}


As you’ll possibly recall, the two source files listed above are all that you need to build a simple file uploading application with PHP that has the capacity to display relevant data about the file uploaded. Not too difficult to grasp, right?

Well, at this point, I showed you how to create a basic file uploading system by using a couple of simple source files. So the next thing that I’m going to teach you will be how to incorporate an effective error checking module into the system in question, which will extend its existing functionality.

Want to see how this will be done? Great! Click on the link below and keep reading.

{mospagebreak title=Creating an effective error handling module}

As I said in the previous section, the $_FILES array stores a predefined set of error codes when a file upload has been performed. This facilitates the development of an error checking mechanism for keeping track of all the possible failures that might occur during a specific file upload.

However, this will be better understood through an example. Please take a look at the signature of the following file uploading script, which implements a rudimentary error checking module capable of triggering different exceptions in accordance with the type of error caused when a file has been uploaded to the web server.

The corresponding code sample is as follows:


// example on checking file uploading errors with the $_FILES array


try{

if($_POST['send']){

// set upload directory (for Windows users)

$uploadDir=’C:uploaded_files';

// set destination of uploaded file

$uploadFile=$uploadDir.basename($_FILES['userfile']['name']);

if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadFile)){

echo ‘The target file was successfully uploaded!<br />Name of uploaded file: ‘.$_FILES
['userfile']['name'].’.<br />MIME type of uploaded file: ‘.$_FILES['userfile']['type'].’.<br />Size of
uploaded file: ‘.$_FILES['userfile']['size'].’ bytes.<br />Temporary name of uploaded file:
‘.$_FILES['userfile']['tmp_name'];

}

else{

// display error messages when file upload fails

switch ($_FILES['userfile']['error']){

case 1:

throw new Exception(‘Target file exceeds maximum allowed size.’);

break;

case 2:

throw new Exception(‘Target file exceeds the MAX_FILE_SIZE value specified on the upload form.’);

break;

case 3:

throw new Exception(‘Target file was not uploaded completely.’);

break;

case 4:

throw new Exception(‘No target file was uploaded.’);

break;

case 6:

throw new Exception(‘Missing a temporary folder.’);

break;

case 7:

throw new Exception(‘Failed to write target file to disk.’);

break;

case 8:

throw new Exception(‘File upload stopped by extension.’);

break;

}

}

}

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


Things are becoming quite interesting at this point! As you can see, the above file uploading script has now been provided with the ability to trigger different exceptions according to the value stored in the $_FILES['userfile]['error'] array element.

Obviously, the error codes stored in the array element aren’t simply an invention of mine; they’re automatically generated by the PHP engine to keep track of different failures that might arise when a file uploading process is being performed via an HTTP POST request.

Based on this handy error handling mechanism, it’s possible to determine what went wrong during a specific file upload. For instance, the size of the selected file might exceed an allowed limit, or may have an invalid extension, etc. In this case, each possible failure can be easily handled via the $_FILES PHP array, as demonstrated by the previous PHP script.

All right, at this level, you’ve hopefully learned how to incorporate a basic error handling module into the file uploading application developed previously, which helps track different failures that might occur when a specific file is being uploaded to the web server.

Nonetheless, the previous file uploading script looks rather disjointed if it’s not accompanied by the corresponding web form that allows users to browse the files in their client machines. Thus, in the final section of this tutorial, I’ll be listing the complete source code of this recently-improved file uploading application, including the web form in question.

So, take a deep breath and read the following lines. 

{mospagebreak title=Listing the complete source code of the improved file uploading application}

As I promised in the section that you just read, I listed the complete definitions corresponding to the two source files that comprise this basic file uploading PHP 5 application. Here they are:


(definition of ‘upload_form.htm’ file)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Uploading files with PHP</title>

<style type="text/css">

body{

padding: 0;

margin: 0;

background: #fff;

}

h1{

font: bold 16pt Arial, Helvetica, sans-serif;

color: #000;

text-align: center;

}

p{

font: normal 10pt Arial, Helvetica, sans-serif;

color: #000;

}

form{

display: inline;

}

#formcontainer{

width: 50%;

padding: 10px;

margin-left: auto;

margin-right: auto;

background: #eee;

border: 1px solid #666;

}

</style>

</head>

<body>

<h1>Uploading files with PHP</h1>

<div id="formcontainer">

<form enctype="multipart/form-data" action="upload_file.php" method="post">

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

<p>File to upload <input name="userfile" type="file" />

<input type="submit" name="send" value="Upload File" /></p>

</form>

</div>

</body>

</html>



(definition of ‘upload_file.php’ file)


try{

if($_POST['send']){

// set upload directory (for Windows users)

$uploadDir=’C:uploaded_files';

// set destination of uploaded file

$uploadFile=$uploadDir.basename($_FILES['userfile']['name']);

if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadFile)){

echo ‘The target file was successfully uploaded!<br />Name of uploaded file: ‘.$_FILES
['userfile']['name'].’.<br />MIME type of uploaded file: ‘.$_FILES['userfile']['type'].’.<br />Size of
uploaded file: ‘.$_FILES['userfile']['size'].’ bytes.<br />Temporary name of uploaded file:
‘.$_FILES['userfile']['tmp_name'];

}

else{

// display error messages when file upload fails

switch ($_FILES['userfile']['error']){

case 1:

throw new Exception(‘Target file exceeds maximum allowed size.’);

break;

case 2:

throw new Exception(‘Target file exceeds the MAX_FILE_SIZE value specified on the upload form.’);

break;

case 3:

throw new Exception(‘Target file was not uploaded completely.’);

break;

case 4:

throw new Exception(‘No target file was uploaded.’);

break;

case 6:

throw new Exception(‘Missing a temporary folder.’);

break;

case 7:

throw new Exception(‘Failed to write target file to disk.’);

break;

case 8:

throw new Exception(‘File upload stopped by extension.’);

break;

}

}

}

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


That’s all for now. With the two above source files at your disposal, you have the proper material to build your own file uploading application in PHP 5. Of course, there’s plenty of room to improve the business logic of this still immature file uploader, but this can be a neat challenge for your programming skills.

Final thoughts

In this third part of the series, I showed you how to improve the file uploading application built during the two preceding articles by incorporating an effective error handling module into it. It can be easily customized to suit your personal needs.

Yet the application in its current incarnation still looks pretty basic. But there’s no reason to feel down. In the upcoming tutorial, I’ll be demonstrating how the complete source code of this file uploader can be encapsulated within a user-defined PHP function. This way it becomes reusable over time.

Don’t miss the next article!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan