Developing a Modular Class For a PHP File Uploader

If you’re a PHP programmer who needs to learn the basic concepts surrounding the implementation of file uploads via the HTTP protocol, then look no further, because you’ve come to the right place. Welcome to the final installment of the series “Building file uploaders with PHP 5.” In a step-by-step process, this series teaches you how to build several PHP-driven file uploading applications by using not only a procedural approach, but the object-oriented paradigm as well.

Now that you’re aware of the topic that’s covered by this series of articles, it’s time to refresh what was discussed in the last tutorial. As you’ll probably recall, during that particular part of the series, I went through the development of a custom PHP function, called “uploadFile()”, which, as its name implies, came in handy for uploading a selected file to a web server via a simple web form.

Apart from performing the file uploading process itself, the aforementioned PHP function was provided with the capacity to throw exceptions in response to different errors that might arise when a file is being uploaded to the web server. In this way, it implements a basic, yet effective, error handling mechanism.

So far, so good. At this stage, you’ve hopefully recalled how to build an expandable file uploading application with PHP 5 that uses only one custom function to transfer a target file from a client machine to a predefined web server. However, in the beginning, I said that I was going to teach you how to develop a brand new file uploading application using an object-oriented approach.

Therefore, this last part of the series will be entirely focused on building a highly modular PHP 5 class. It will encapsulate all the business logic required to perform file uploads via HTTP behind its API.

So, let’s not waste more time in preliminaries and start learning how to create a file uploading class with PHP 5. Let’s get going!

{mospagebreak title=Handling file uploads using the object-oriented paradigm}

Simply put, the first step that I’m going to take concerning the creation of a modular file uploading class with PHP 5 will consist of defining the skeleton of the class in question, while also implementing its pertinent constructor. This way you can grasp how it works more easily.

Having said that, take a close look at the signature of the following brand new file uploading class, which, driven by my astounding creativity (I’m kidding), I called “FileUploader.” Here it is:


// define ‘FileUploader’ class


class FileUploader{

private $uploadFile;

private $name;

private $tmp_name;

private $type;

private $size;

private $error;

private $allowedTypes=array
(‘image/jpeg’,’image/gif’,’image/png’,’text/plain’,’application/ms-word’);

public function __construct($uploadDir=’C:uploaded_files’){

if(!is_dir($uploadDir)){

throw new Exception(‘Invalid upload directory.’);

}

if(!count($_FILES)){

throw new Exception(‘Invalid number of file upload parameters.’);

}

foreach($_FILES['userfile'] as $key=>$value){

$this->{$key}=$value;

}

if(!in_array($this->type,$this->allowedTypes)){

throw new Exception(‘Invalid MIME type of target file.’);

}

$this->uploadFile=$uploadDir.basename($this->name);

}

// upload target file to specified location in the web server

public function upload(){

/ / code to perform file uploads goes here

}

}


As you can see, the structure of the above “FileUploader” class looks quite simple, since it’s comprised of only two methods: the corresponding constructor and an additional one, called “upload()”, which, for now, hasn’t been concretely implemented.

Returning to the constructor, you can clearly see that this method accepts the directory in the web server where the pertinent uploaded file will be finally moved as its unique input parameter. In addition, it performs a few other useful initialization tasks, such as checking to see whether or not the inputted directory is valid, and whether or not the MIME type of the target file is allowed.

In this case, I instructed the class to accept only the most common image MIME types, like JPG and GIF, and a couple of additional ones as well, including “text/plain” and “application/msword.” But this condition can be easily modified to either accept more types or, on the other hand, to refuse some of the valid ones.

All right, at this point you’ve hopefully grasped the logic implemented by the constructor of the previous “FileUploader()” class. Therefore, it’s time to implement the only method of this class that remains undefined, that is the one called “upload()”.

However, to learn the details about how this class method will be implemented in a useful fashion, you’ll have to read the following section. Don’t you worry, since it’s only one click away.

{mospagebreak title=Completing the definition of the FileUploader class}

As you saw in the previous section, the only method of the pertinent “FileUploader” class that remains undefined is the one called “upload().” However, as its name suggests, the method should encapsulate all the logic required to upload a selected file to its final location in the web server, as well as check if this process has been performed successfully.

Therefore, taking into account all of the tasks that must be accomplished by the  “upload()” class method, below I listed its complete definition, which looks like this:


public function upload(){

if(move_uploaded_file($this->tmp_name,$this->uploadFile)){

return true;

}

// throw exception according to error number

switch($this->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;

}

}


In this case, if you had the chance to read the preceding article of this series, you’ll find the implementation of the above “upload()” class method quite simple to grasp, since it looks very similar to the “uploadFile()” procedural function defined in that tutorial. In either case, the prior method uses the “move_uploaded_file()” PHP built-in function to transfer the target file to its final location in the web server, assuming that the file upload has been completed successfully.

On the other hand, if this process fails for whatever reason, an exception will be triggered, indicating the cause of this error. Quite easy to grasp, right?

Having explained how the previous “upload()” method does its business, I’m now going to list the complete signature of the “FileUploader” class, only this time including the method in question. Here’s how this class now looks:


class FileUploader{

private $uploadFile;

private $name;

private $tmp_name;

private $type;

private $size;

private $error;

private $allowedTypes=array
(‘image/jpeg’,’image/gif’,’image/png’,’text/plain’,’application/ms-word’);

public function __construct($uploadDir=’C:uploaded_files’){

if(!is_dir($uploadDir)){

throw new Exception(‘Invalid upload directory.’);

}

if(!count($_FILES)){

throw new Exception(‘Invalid number of file upload parameters.’);

}

foreach($_FILES['userfile'] as $key=>$value){

$this->{$key}=$value;

}

if(!in_array($this->type,$this->allowedTypes)){

throw new Exception(‘Invalid MIME type of target file.’);

}

$this->uploadFile=$uploadDir.basename($this->name);

}

// upload target file to specified location

public function upload(){

if(move_uploaded_file($this->tmp_name,$this->uploadFile)){

return true;

}

// throw exception according to error number

switch($this->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;

}

}

}


At this moment, you’ll have to agree with me that the above “FileUploader” class is much more useful, while maintaining a high level of modularity. Of course, there’s the possibility that you may want to add some additional logic to some of its existing methods, or even define new ones, but this will depend exclusively on your personal requirements.

With the previous “FileUploader” class defined completely, it’s time to see how it can be used in the context of a hands-on example. Thus, in the last section of this tutorial, I’ll be setting up this example for you, completing this series on handling file uploads with PHP 5.

Click on the link below and keep reading. We’re almost done!

{mospagebreak title=Testing the FileUploader class}


As I promised in the section that you just read, below I coded a comprehensive hands-on example that demonstrates how the recently created “FileUploader” class can be used to upload a hypothetical file to the web server.

Here’s the corresponding code sample, which assumes that the file uploading class resides in a separate file called “fileuploader.php”:


try{

if($_POST['send']){

require_once ‘fileuploader.php';

$fileUploader=new FileUploader();

if($fileUploader->upload()){

echo ‘Target file uploaded successfully!';

}

}

}


/* displays the following:

Target file uploaded successfully!

*/

catch(Exception $e){

echo $e->getMessage();

exit();

}


And finally, in order to complement the previous practical example, I included the definition of all the source files required to get this object-based file uploading application working as expected:


(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 ‘fileuploader.php’ file)


<?php


class FileUploader{

private $uploadFile;

private $name;

private $tmp_name;

private $type;

private $size;

private $error;

private $allowedTypes=array
(‘image/jpeg’,’image/gif’,’image/png’,’text/plain’,’application/ms-word’);

public function __construct($uploadDir=’C:uploaded_files’){

if(!is_dir($uploadDir)){

throw new Exception(‘Invalid upload directory.’);

}

if(!count($_FILES)){

throw new Exception(‘Invalid number of file upload parameters.’);

}

foreach($_FILES['userfile'] as $key=>$value){

$this->{$key}=$value;

}

if(!in_array($this->type,$this->allowedTypes)){

throw new Exception(‘Invalid MIME type of target file.’);

}

$this->uploadFile=$uploadDir.basename($this->name);

}

// upload target file to specified location

public function upload(){

if(move_uploaded_file($this->tmp_name,$this->uploadFile)){

return true;

}

// throw exception according to error number

switch($this->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;

}

}

}

?>



(definition of ‘upload_file.php’ file)


<?php


try{

if($_POST['send']){

require_once ‘fileuploader.php';

$fileUploader=new FileUploader();

if($fileUploader->upload()){

echo ‘Target file uploaded successfully!';

}

}

}


catch(Exception $e){

echo $e->getMessage();

exit();

}

?>


As usual with many of my articles on PHP web development, feel free to tweak the entirety of the code samples shown in this tutorial in order to acquire a more solid background on handling file uploads with PHP 5.

Final thoughts

Sad but true, this is the end of this series. Hopefully the whole experience has been instructive. In the different tutorials, I showed you distinct approaches to building several file uploading applications with PHP 5, ranging from using procedural methodologies to utilizing the object-oriented paradigm.

See you in the next PHP development tutorial!

[gp-comments width="770" linklove="off" ]

chat