Creating a multiple files Uploader class in Php

Author: Evan xg

Hi There, I am Evan-XG a C# and Php programming Guru. I have been developing desktop applications for three years. I started web application just two years ago. I really enjoy learning new things and sharing my thoughts.

Creating a multiple files Uploader class in Php

Uploading a file is an important task that a web developer should know and be aware of all those security issues that it can bring. In this tutorial I am going to show how you can design and implement a Php class to upload multiple files on your server file system.

To provide an upload feature in an application a developer needs to be aware of two main things: first the type of the file, second the size that is authorized. Also we will need the directory where we are planning to store the uploaded file and of course a variable to report what happened. In our class we will have five member variables.

Here is the class skeleton :

 
 
<?php
class Upload {
//To get the maximum file size allow by the server
private $filemaxsize;
//The directory where the file will be uploaded
private $dir;    
 
//To hold the type of files that we accept since the restriction
//in our form can be hacked by the spoofed form method
private $type=array();  
 
//this will hold the global variable $_FILES[] from the  form submited
private $files=array();
 
//this variable will help us to store errors that occure for each files
private $report=array(); 
 
//this is one of the php feature that allow us to set a default
//message when trying to echo an instance of our class
Public function __tostring() {}
 
// the constructor that you probably know
//in this constroc tor we need to provide the destination
//directory and the various kind of file that we accept
//you are not going to accept .php files !
Public function __construct($directory,$type) {}
 
//this private method will be a kind of helper to set the
//$filemaxsise member wich is defined in the php.ini file
Private function setFileMaxSize() { }
 
//the miror to help us to know what is the maximum size
//allowed by our server
//this is just for helping us to know, but you can use it
//when creating your upload form ass well
Public function getFileMaxSize() {}
 
//this method will retrieve all those errors that occure
Public function getReport() {}
 
//this method will allow us to upload the files
Public function Upload($files) {}
 
}
 

Now in the implementation: the _tostring method will only output a sentence to show us the unhappiness of the object; in the constructor we set the $dir member to the $directory variable passed as first parameter and the authorised type of file variable to it mirror. Next we set the $filemaxsize member by calling the private method setMaxFileSize()
Now let’s explain how we implement this private method setMaxFileSize().
The first instruction of this method simply stripes the content given by the call to the ini_get () function which takes string as parameter to specify which initialisation value we want from the php.ini file: post_max_size in our case. The second line turn in lower case the value and return of the last character. Actually when we call ini_get (' post_max_size'), we will get something like this 123 M (just an example )and those lines will manipulate this value to give back $val=123 and $last=m.
Next we multiply by 1024 for each case. But notice how we do not put a break statement after each case because our goal is to convert from any dimension (Gb, Mb or Kb ) to byte so if our switch start on (m) the second case it will perform the first conversion to Kb and from Kb to B; finally we set the internal class member $filemaxsize.
The next two methods return just respectively the value of $filemaxsize and $report class member.

Now let’s talk about the main method: In this method we will explain through the code itself

 
 
//this method takes the global array $_FILES as parameter
 Public function Upload($files) {
//checks if we are not dealing with an empty array
if(!empty($files))
{
//we count the number of the file
$nbFiles  = count($files['file ']['tmp_name']);
//initialise the error report array to an empty array
$report=array();
// we begin a loop to perform many instructions on each file
for($i = 0; $i<$nbFiles ; $i++)
{
//we check if the current files is actually an uploaded file
if(is_uploaded_file($files['file ']['tmp_name'][$i]))
{
//we get the file name note that the array key (file) is the
//name of the input field in the form therefore when creating
//a form the file input fields should be named : file[]
$name     = $files['file']['name'][$i];
// we get the file temporary name
$tmp_name = $files['file']['tmp_name'][$i];
//we get the file type diferrent from the extention
$type_file = $files['file']['type'][$i];
//we get the file errors content
$error    = $files['file']['error'][$i];
//now we clean the file name to get rid of special characters if it exist
$clean_name = strtolower(basename($name));
$clean_name = preg_replace('/[^a-z0-9.-]/', '-', $clean_name);
//we check if the file has the normal size range that we expect
if($files['file']['size'][$i]>=$this->filemaxsize)
{
//if the file size is abnormal we set in the report array size=false
//for the curent file
$report[$i]['size']=false;
}
//we check for the type now
$test_type=false;
for($j=0;$j<count($this->type);$j++)
{
//debug mode: echo $type_file; will show you the file type because
// it is not obvious for you to know that the type of .pdf files
// is application/pdf  .
//if the type exist in the array we set  $test_type to true
if(($this->type[$j])==$type_file)
{
$test_type=true;
}
}
if ($test_type==true)
{
//now if the file type is authorised we try to move the file
if(move_uploaded_file($tmp_name, $this->dir.$clean_name))
{
}
else
{
//if the file cannot be moved , we set ass an error
$report[$i]['move']=false;
}
}
else
{
//here if the file type was not authorised we set
//the report to false for the type
$report[$i]['type']=false;
}
}
//we clear the cash because we have used some functions
//that cashes their values so if we don’t
//we will get some unexpected errors (the same value will be
//given in the next call to those functions no matter the context)
clearstatcache();
 
}
$this->report=$report;
}
else
{
	return false;
}
//we analise the report array variable to see if it contains something
if(count($report)==0)
{
return true;
}
else
{
return false;
}
}
 

You can download the final ready to use class; I hope this tutorial helps you in some ways and please help the blog,the community by sharing the content.

Posted in: Blog, Tutorials On Saturday, December 12th, 2009 At 7:34 pm

2 Responses to “Creating a multiple files Uploader class in Php”

  1. [...] Creating a multiple files Uploader class in Php [...]

  2. DOUG says:


    Medicamentspot.com. Canadian Health&Care.No prescription online pharmacy.Best quality drugs.Special Internet Prices. High quality drugs. Buy pills online

    Buy:SleepWell.Acomplia.Prozac.Nymphomax.Buspar.Wellbutrin SR.Female Pink Viagra.Ventolin.Amoxicillin.Cozaar.Benicar.Female Cialis.Lasix.Lipothin.Zocor.Zetia.Seroquel.Advair.Aricept.Lipitor….

Leave a Reply