Class 8 – Uploading Files to Server in PHP
Posted: July 22nd, 2009 | Author: amos | Filed under: php, server | Tags: class 8 | No Comments »Some sites allow users to upload files to the server. Most often, this is the case for sites that allow users to upload images. But the same technique is used regardless of the type of file. Uploading files of any type, be they images, audio files, video files, text files, or any other type, is a singular process.
This example shows how to allow users to upload files to the server. As with any site, it all starts with the XHTML. Click here to see this example code in action.
An XHTML page with a form
When uploading files to the server, it is absolutely necessary to give the <form> tag an extra attribute: enctype=”multipart/form-data”. This tells the server that it should expect to receive not only text in the form data, but also possibly a file as well. Omitting this extra attribute is a common mistake.
Here is an example XHTML page with a file upload form on it. We’ll call it “index.html“. The especially relevant bits for this example are the <form> tag, and the <input type=”file”> tag:
<?xml version="1.0" encoding="utf-8"?> <!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> <title>File Upload Example</title> <link rel="stylesheet" type="text/css" href="styles/main.css" /> </head> <body> <div id="container"> <h1>File Upload Example</h1> <p>Please upload an image:</p> <form action="process_file.php" method="POST" enctype="multipart/form-data"> <input type="file" name="uploadfile"> <br /><br /> <input type="submit" value="Upload!"> </form> </div><!-- end container --> </body> </html>
When the user clicks the submit button, the data entered into the form is sent along with an HTTP POST request to the server for the script, “process_file.php”. This we surmise from the “method” and “action” attributes of the <form> tag.
A PHP script to process the uploaded file
The following code is from “process_file.php“, which is the PHP script that receives the data passed along with the HTTP POST request, and decides what to do with it.
<?php
require_once("Uploader.class.php");
//create a new instance of the Uploader class
//the constructor function for the Uploader class takes three parameters: the "name" attribute of the <input type="file" name="..."> field, the subdirectory where you want to store the files, and the maximum file size allowed
$uploader = new Uploader("uploadfile", "files", "10M");
//try to do the upload
if ($uploader->upload()) {
//it worked... so get the new location of the file from the $uploader->getPermanentPath() function
$path = $uploader->getPermanentPath();
//redirect to success page, and pass the new path along
header("Location: success.php?path=" . urlencode($path));
}
else {
//it didnt work! so get the new error message from the $uploader->getError() function
$error = $uploader->getError();
//redirect to failure page, and pass the error message along
header("Location: failure.php?error=" . urlencode($error));
}
?>
Let’s analyze this file. The first thing we do is require the inclusion of another file, named “Uploader.class.php”. This file is an object-oriented bit of PHP code that I have written. This Uploader class file contains the code that does the dirty work of file uploading.
The nice thing about object oriented code is that it is built to be taken for granted (click here if you’re interested in a brief intro to object-oriented concepts.) This is one of the core philosophies of object-oriented coding: different processes should run independently of one another, and the internal workings of each process should not matter to the functioning of the other processes. This is known as “encapsulation”. So in this case, I will not explain how this class works. The code is well commented if you want to look for yourselves. I will just describe how it should be used.
Once we have included the Uploader class file, we create an Uploader object. To do so requires passing three pieces of data to the Uploader “constructor function” (read here for a brief intro to how to do object-oriented programming in PHP)
$uploader = new Uploader("uploadfile", "files", "10M");
- The first parameter is the value we gave the “name” attribute of the <input type=”file” name=”…” /> tag in the XHTML form, in this case it is “uploadfile”.
- The second parameter is the subdirectory on the server where we want to store any uploaded files… you’ll see on the server that we have set up a “files” subdirectory in this project folder. (Note: This folder must allow web browsers to write data to it. You can use a file-transfer program such as WinSCP or Cyberduck to make sure the permissions for this folder allow “Others” to “Write” to it. Usually this can be done by right-clicking on the folder in WinSCP, or Control-clicking on the folder in CyberDuck, and selecting the “Properties” or “Info” menu in WinSCP and CyberDuck respectively)
- The last parameter is an option maximum file size that you want to allow users to upload, in this case 10M.
Now that the object is set up, we try to do the upload, and we test to see if it worked or not.
if ($uploader->upload()) {
//... it worked ...
}
else {
//... it failed ...
}
If the upload was successful, we redirect the browser to a “success.php” confirmation page. We also pass along the path of the newly uploaded file on the server to the success.php script.
If the upoad failed, we redirect the browser to a “failure.php” page that explains that an error occurred, and we pass along an error message as part of the request for that failure.php script.
The success confirmation page
The success.php confirmation page simply shows a user-friendly message indicating that the upload was successful. The PHP script on this page retrieves the data that was passed along with the HTTP GET request for the page. This data is the path of the newly uploaded image file on the server. The script on this page uses that path as the “src” attribute of an <img> on the page, which makes the uploaded image appear on the page.
<?php echo "<?" ?>xml version="1.0" encoding="utf-8"?> <!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> <title>Success! File Uploaded</title> <link rel="stylesheet" type="text/css" href="styles/main.css" /> </head> <body> <div id="container"> <h1>Success! File Uploaded</h1> <p>Thanks. Your image has been successfully uploaded to <?php echo $_REQUEST['path'] ?></p> <a href="<?php echo $_REQUEST['path']; ?>"> <img src="<?php echo $_REQUEST['path'] ?>" /> </a> </div><!-- end container --> </body> </html>
The failure error page
The failure.php error page simply shows a user-friendly error message indicating that the upload was unsuccessful. The PHP script on this page retrieves the data that was passed along with the HTTP GET request for the page. This data is the error message that was output by the Uploader object.
<?php echo "<?" ?>xml version="1.0" encoding="utf-8"?>
<!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>
<title>Failure! File Not Uploaded</title>
<link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>
<body>
<div id="container">
<h1>Failure! File Not Uploaded</h1>
<p>Your image failed to upload</p>
<p><?php echo $_REQUEST['error'] ?></p>
<p>
<a href="index.html">try again</a>
</p>
</div><!-- end container -->
</body>
</html>


Leave a Reply