Home arrow PHP arrow Page 4 - Developing a Modular Class For a PHP File Uploader

Testing the FileUploader class - PHP

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.

TABLE OF CONTENTS:
  1. Developing a Modular Class For a PHP File Uploader
  2. Handling file uploads using the object-oriented paradigm
  3. Completing the definition of the FileUploader class
  4. Testing the FileUploader class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 3
April 16, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement


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!



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: