Building File Uploaders with PHP 5

My goal here is simply tackling file uploads from a hands-on point of view and discarding all of those additional configuration settings that must be performed in the web server. Therefore, in this series of articles, I’m going to show you how to build some file uploading mechanisms with PHP 5, which, due their intrinsic modularity, can be easily integrated into other existing PHP applications with minor hassles.

If you’re a PHP developer who has built a certain number of web applications, then it’s quite probable that you’ve already worked with HTTP file uploads. They play a relevant role in the business logic of any PHP program that permits users to transfer specific files from their client computers to a web server via a web-based front-end, which is generally represented by an online form.

Indeed, file uploads have been supported by PHP for a long time. Even though they’re relatively easy to implement in real world conditions by way of the useful set of native functions provided by the language, at the same time they require you to deal with a number of settings, which, in normal conditions, are beyond the scope of an average PHP programmer.

As you might know, handling HTTP file uploads with PHP not only implies that they must first be enabled on the php.ini file, but also that it’s necessary to create a complete “writable” environment in the web server so user files can be uploaded seamlessly into a specified directory without getting any intimidating access-denied server responses.

Of course, setting up this friendly environment in the web server properly isn’t always so feasible for a PHP developer who works with a shared hosting service, since this process naturally demands the intervention of a system administrator. But despite the issues, in general terms, file uploads can be implemented quite easily with PHP.

As you’ll see in the next few lines, first I’m going to teach you how to handle file uploads using a procedural approach, and then, with the topic well underway, by way of the object-oriented paradigm.

Having introduced you to the subject of this article series, let’s learn how to implement file uploads with PHP 5. Let’s begin now!

{mospagebreak title=Implementing file uploads with PHP: the $_FILES superglobal array}

It’s practically impossible to cover file uploads in PHP 4/5 without examining one of the key elements involved in this process in detail. Yes, you guessed right! In this case, I’m talking about the $_FILES superglobal PHP array (or its equivalent in earlier versions, $HTTP_POST_FILES), which handles every parameter created by PHP with precision, such as when a file is being uploaded to the server via the HTTP protocol.

But it’s time to get rid of this rather boring theory and see how the $_FILES array stores all the information related to an uploaded file. The following list shows each element that makes up this array along with a brief description of what it does (notice that the explanations assume that the web form used to upload a file contains a field named “userfile”):


$_FILES['userfile']['name'] (Specifies the original name of the file being uploaded on the client computer).

$_FILES['userfile']['type'] (Specifies the MIME type of the file being uploaded, for instance, “image/jpeg”).

$_FILES['userfile']['size'] (Indicates the size in bytes of the file being uploaded).

$_FILES['userfile']['tmp_name'] (Indicates the temporary name used by the web server to store the uploaded file).

$_FILES['userfile']['error'] (Specifies the error code associated with a specific file upload).


Now that I have listed the elements that make up the $_FILES superglobal array, you can see more clearly, based on the above descriptions, that PHP provides all the parameters required to perform file uploads with minor hassles.

It’s important to stress that the array in question also includes an element that stores an error number associated with the file uploading process, which means that it’s pretty simple to implement the logic necessary to handle these eventual errors. But I’m getting ahead of myself, since this topic will be covered in an upcoming tutorial of the series.

So, at this point, I have provided you with a quick overview of the different elements included in the $_FILES superglobal array, which stores all the information related to a specific file uploading process. But you’re probably wondering how this array can be used to perform a file upload within a PHP script, right?

Well, first it’s necessary to build a simple front-end that permits users to select a particular file in the client machine, and then upload it to the web server. Thus, considering this requirement, in the section to come I’m going to show you how to create a simple web form that will perform this task in a straightforward way.

Naturally, to see how this file uploading form will be coded, you’ll have to click on the link below and keep reading.

{mospagebreak title=Building a simple file uploading form}


As I explained in the previous section, the first step required to perform a file upload with PHP consists of building a basic online form, which lets users select a target file and then upload it to the server’s temporary directory.

Having described how the file uploading online form is going to function, I’m going to construct a basic web page that includes the web form in question. This way I will provide users with a basic front-end that allows them to upload files to a web server in a simple way.

That being said, here’s the definition of the web document that contains the aforementioned file uploading form:


<!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="20000" />

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

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

</form>

</div>

</body>

</html>


As you can see, the structure of the above web page is really simple, since the most important element that it contains is the online form that I mentioned earlier, which will come in handy when uploading a selected file to the web server.

Speaking more specifically, there are two relevant details we need to highlight here with reference to how the previous web form has been coded. The first one is its “enctype” attribute, which must have a value of “multipart/form-data” so the web server will be able to correctly process the corresponding form input and upload the selected file into a temporary directory.

The second one is the MAX_FILE_SIZE hidden field. The reason for including this additional form element is to establish a maximum size in bytes for the file being uploaded (in this case, I specified a limit of 20,000 bytes). As you’ll see later on, once the pertinent file uploading form has been submitted, it’s possible to check the value of this field with PHP and reject all the files that exceed this size. Not too complex to grasp, is it?

So far, so good. At this stage, I’ve shown you how to build a basic web form that allows users to browse files in their client machines and upload one of the them to a temporary directory on the web server. What’s the next step?

Well, here’s where things become really interesting! As you may have noticed, the previous online form points its “action” attribute to a file called “upload_file.php,” meaning that this one will be responsible for moving the file that was just uploaded to a predefined directory in the server. This way it completes the file uploading process.

To see the logic that will be implemented with this PHP file, please go ahead and read the following section. It’s only one click away.

{mospagebreak title=Processing a file upload with PHP}

Handling a file upload with PHP is a much simpler process than you might think. The core logic that must be implemented to perform this process is simply moving the user file that resides on a temporary directory of the web server to its final location.

Of course, as with many things in PHP programming, there are several ways to accomplish a file upload and each of them generally involves the use of different PHP native functions. However, in this particular case, I’m going to use the “move_uploaded_file()” function, which moves an uploaded file to a new location in the web server.

In simple terms, this function verifies that the target file has been uploaded by way of an HTTP POST request. And if this condition is true, the file in question is moved to the final location.

Now that you have a clear idea of how the “move_uploaded_file()” function works, pay close attention to the following PHP script. It uses this function to move an uploaded file to a predefined directory in the web server:


// basic example on uploading a file to the server via HTTP
 

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

}

else{

echo ‘Error uploading target file!';

}

}


If you study the above PHP script in detail, you’ll understand how it works. Basically, it checks to see if the corresponding file uploading form has been submitted and uses the aforementioned “move_uploaded_file()” PHP built-in function to move the uploaded file from its temporary directory to a predefined location in the web server.

In this case, I decided to move all of the valid uploaded files to the “C:uploaded_files” directory, which obviously is valid only for Windows users. If you’re using another operating system, this option can be modified to fit your specific requirements.

Finally, if the uploaded file can’t be moved to the predefined directory, a trivial error message is displayed on the browser. Of course, one of the most important things to highlight concerning the definition of the previous PHP script is the way that some elements of the $_FILES superglobal PHP array are utilized to complete the pertinent file uploading process. Now do you realize how the different pieces fit with each other when it comes to uploading files with PHP? I bet you do!

In addition, I’d like to wrap up this tutorial by showing you the complete source code of the two files that compose this basic file uploading PHP application so you can examine them more easily. 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="20000" />

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

}

else{

echo ‘Error uploading target file!';

}

}


Before starting to upload files with PHP, remember to check your php.ini settings in addition to assigning the appropriate permissions to the corresponding destination directory in the web server.

Final thoughts

In this first tutorial of the series, I showed you how to build a basic file uploading application with PHP. It’s something that can be useful if you’re just starting to use this handy language or if you want to fill some possible gaps with reference to this topic.

However, when it comes to handling file uploads with PHP, I’m only scratching the surface. The application that I developed earlier lacks some important features, such as adequate control over the type and size of the file being uploaded as well as the inclusion of a solid error handling module.

Of course, all of these issues will be addressed in the next part. So you don’t have any excuses to miss it!

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

chat