Defining a Custom Function for File Uploaders with PHP 5

In the next few lines I’m going to show you how to wrap the file uploading application built in the previous article of the series into a single custom PHP function. This will turn it into a more maintainable and reusable piece of code.

Learning how to implement file uploads with PHP is undoubtedly one of those things that you have to tackle sooner or later, during your life as PHP developer. And if you’re not armed with a decent background on this topic, there’s the possibility that by the time you finish building your first file uploading application, you will have suffered serious hair loss.

However, there’s no need to expect this, since in this series of articles, you’ll find the right pointers to help you start implementing file uploads with PHP 5. And as always, you’ll be provided with copious practical examples that will help you understand this useful topic from a hands-on point of view.

Now that you’ve been introduced to the principal subject of this article series, let me quickly rehash the items that I discussed in the preceding installment, in case you haven’t read it yet. In the course of the mentioned tutorial, I went through the development of a basic error handling module that came in handy for keeping track of all the errors that might occur during a specific file uploading process.

What’s more, the logic implemented by this simple error checking module was built around the functionality provided by the $_FILES super global PHP array, since it uses one of its elements to store different error codes that are associated with a particular file uploading failure. In this way, it was pretty simple to instruct the module in question to throw several exceptions that could be neatly caught by a typical “try-catch()” block.

So far, so good. At this point, I should assume that building an error checking mechanism that is aimed at tracking all the failures that might arise when uploading a selected file to a web server, is now a familiar process to you. Therefore, it’s time to introduce a few other improvements to the pertinent file uploading application that you learned in the previous tutorial.

Let’s continue this educational journey now!

{mospagebreak title=The full source code of the previous file uploading application}

Before I show you how to create a reusable custom PHP function based on the file uploading script developed in the previous chapter of the series, first I’d like to list its full source code, so that you can recall how it worked as a standalone module.

Please take a quick look at the following pair of source files, which, as I said before, comprised the primary structure of the file uploading application previously created:

(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();

}


As you’ll surely recall, the source files listed above comprise the core of the extensible file uploading application built in the preceding article of this series. Of course, the most important point to stress here, with reference to the logic implemented by the prior script, is its ability to throw a certain number of exceptions in accordance with all the potential errors that might arise after uploading a particular file to the web server.

The way that I constructed this error checking mechanism is quite simple to follow. Thus, I’m guessing that you shouldn’t have major problems grasping its underlying logic.

So far, so good. Now that you’ve recalled how the file uploading application looked originally, it’s time to see how it can be encapsulated into a custom PHP function, with the purpose of turning it into a reusable and compact piece of code.

Sounds pretty interesting, right? However, to see the full details on how this will be done, you’ll have to click on the link below and read the following section.

{mospagebreak title=Putting the file uploading script into the “uploadFile()” custom PHP function}

True to form, encapsulating the previous file uploading script into a single custom PHP function is a straightforward process that can be performed without major problems, since most of the pertinent business logic has already been implemented before.

However, let me go one step further and show you the signature of this brand new user-defined PHP function, called “uploadFile().” It looks like this:


// define ‘uploadFile()’ function


function uploadFile($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.’);

}

if(!in_array($_FILES['userfile']['type'],array
(‘image/jpeg’,’image/gif’,’image/png’,’text/plain’,’application/msword’))){

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

}

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

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

return true;

}

// throw exception according to error number

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;

}

}


As you can see, the above “uploadFile()” PHP function encapsulates all the logic required to upload a selected file to the web server within its structure. And it takes up the directory in the web server as its unique input parameter – where the file in question will be moved.

Based on this concept, the function checks to see if this directory is valid or not, and then uses “move_uploaded_file()”, a PHP built-in function, to complete the pertinent file uploading process. In addition, any error that might occur when these tasks are performed will trigger different exceptions that can be easily caught by a conventional “try-catch()” block. Quite simple to understand, right?

Well, at this point I’m pretty sure that you’ve grasped how the previous “uploadFile()” does its thing. So I’m going to demonstrate how it can be used in the context of a practical example. You will see how useful it can be, when it comes to uploading a file via PHP.

This hands-on demonstration will take place in the next section, so click on the link below and keep reading.

{mospagebreak title=Putting the uploadFile() PHP custom function to work}

In consonance with the concepts that I expressed in the prior section, the best way to demonstrate the capacity of the recently-defined “uploadFile()” function is by putting it to work in the context of a practical example. Therefore, suppose for a moment that I already coded a simple web form for letting users browse different files on their machines and uploading only one of them to the web server, like the one shown in the beginning of this tutorial.

As you know, the sample (X)HTML that contains this online form would look like this:


<!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>


Now that I’ve coded the above file uploading web form, the only thing that remains undone is defining the pertinent “upload_file.php” file. This time it will include the definition of the previous “uploadFile()” custom function that you saw before.

Given that, the aforementioned PHP file would now look like this:


<?php

// define ‘uploadFile()’ function

function uploadFile($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.’);

}

if(!in_array($_FILES['userfile']['type'],array
(‘image/jpeg’,’image/gif’,’image/png’,’text/plain’,’application/msword’))){

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

}

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

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

return true;

}

// throw exception according to error number

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;

}

}

try{

if($_POST['send']){

// call ‘uploadFile()’ function

if(uploadFile()){

echo ‘Target file uploaded successfully!';

}

}

}

catch(Exception $e){

echo $e->getMessage();

exit();

}

?>


Did you realize how easy was to build a file uploading application using the “uploadFile()” PHP custom function listed previously? I’m sure you did! In this case, only two source files are required to get this application working. These can be quickly integrated into other existing PHP programs.

All right, at this point, I’ve shown you how to create an extensible file uploading script that only uses a simple PHP custom function to work as expected. Of course, the script has plenty of room to be extended and improved, but this process, due to the intrinsic flexibility offered by the “uploadFile()” function, can be performed in an effortless way.

Final thoughts

That’s all for the moment. In this fourth part of the series, I taught you how to implement a highly-expandable file uploading application by way of a straightforward PHP 5 function that encapsulates all the logic required to perform this task in a few simple steps.

And speaking of logic encapsulation, in the final tutorial of the series, I’ll show you how to construct a file uploading application similar to the one discussed before, but this time using a highly-modular PHP class.

So, if you’re a strong advocate of using the object-oriented paradigm with PHP 5, you simply can’t miss this last article!

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

chat