ptamzz
ptamzz

Reputation: 9365

PHP class for uploading files

I'm trying to upload file using this PHP class available at http://www.finalwebsites.com/snippets.php?id=7 (to view the codes for the class http://pastebin.com/sqbMw4sR)

And I've the following codes in the upload processing file

$max_size = 1024*100; // the max. size for uploading    
$my_upload = new file_upload;

// upload directory
$my_upload->upload_dir = HOME_PATH."users/";

// allowed extensions
$my_upload->extensions = array(".png", ".jpeg", ".jpg", ".gif"); 
$my_upload->max_length_filename = 50;
$my_upload->rename_file = true;

$new_name = "testing" . time();

if(isset($Submit)) {
    $my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
    $my_upload->the_file = $_FILES['upload']['name'];
    $my_upload->http_error = $_FILES['upload']['error'];
    $my_upload->the_mime_type = $_FILES['upload']['type'];

    // because only a checked checkboxes is true
    $r = $_POST['replace'];
    $my_upload->replace = (isset($r)) ? $r : "n";

    // use this boolean to check for a valid filename
    $a = $_POST['check'];
    $my_upload->do_filename_check = (isset($a)) ? $a : "n"; 
    if ($my_upload->upload($new_name)) { 
        // new name is an additional filename information, 
        //use this to rename the uploaded file
        $full_path = $my_upload->upload_dir.$my_upload->file_copy;

        // just some information about the uploaded file
        $info = $my_upload->get_uploaded_file_info($full_path); 
        // ... or do something like insert the filename to the database
    }
}
$error = $my_upload->show_error_string();

According to my understanding, the file should've been uploaded but it neither throws any error nor it is uploaded.

I'm calling this file using ajaxForm (jquery plugin http://malsup.com/jquery/form/#file-upload).

Can anyone please point out what is wrong here?

Upvotes: 5

Views: 13827

Answers (2)

user12199438
user12199438

Reputation: 31

File uploaded to extension named folder in "upload" folder.

HTML:

<form method="post" action="test_act.php" enctype="multipart/form-data">
       <div>
          <span>Choose file</span>  
          <input type="file" name="fileToUpload" id="fileToUpload">
          <br/>
          <input type="submit" name="fupload" id="fupload">
       </div> 
    </form>

test_act.php (Form Action)

<?php 
include ("test_cls.php");
if(isset($_POST['fupload']))
{
    $dirpath="upload";
    $uploader   =   new Uploader();

    $uploader->setExtensions(array('jpg','jpeg','png','gif','doc','docx'));  //allowed extensions list//

    $uploader->setMaxSize(1);                          //set max file size to be allowed in MB//

    $uploader->setDir($dirpath);

    if($uploader->uploadFile('fileToUpload'))          //txtFile is the filebrowse element name //
    {   
        $suc_file  =   $uploader->getUploadName(); //get uploaded file name, renames on upload//
        echo $suc_file." successfully uploaded";
    }
    else                    //upload failed
        echo $uploader->getMessage(); //get upload error message
}
?>

test_cls.php (class):

<?php
class Uploader
{
    private $destinationPath;
    private $errorMessage;
    private $extensions;
    private $maxSize;
    private $uploadName;
    public $name='Uploader';

    function setDir($path){
        $this->destinationPath  =   $path;
    }

    function setMaxSize($sizeMB){
        $this->maxSize  =   $sizeMB * (1024*1024);
    }

    function setExtensions($options){
        $this->extensions   =   $options;
    }

    function setMessage($message){
        $this->errorMessage =   $message;
    }

    function getMessage(){
        return $this->errorMessage;
    }

    function getUploadName(){
        return $this->uploadName;
    }

    function uploadFile($fileBrowse){
        $result =   false;
        $size   =   $_FILES[$fileBrowse]["size"];
        $name   =   $_FILES[$fileBrowse]["name"];
        $ext    =   pathinfo($name,PATHINFO_EXTENSION);

        $this->uploadName=  $name;

        if(empty($name))
        {
            $this->setMessage("File not selected ");
        }
        else if($size>$this->maxSize)
        {
            $this->setMessage("Too large file !");
        }
        else if(in_array($ext,$this->extensions))
        {
            if(!is_dir($this->destinationPath))
                mkdir($this->destinationPath);
            if(!is_dir($this->destinationPath.'/'.$ext))
                mkdir($this->destinationPath.'/'.$ext);

            if(file_exists($this->destinationPath.'/'.$ext.'/'.$this->uploadName))
                $this->setMessage("File already exists. !");
            else if(!is_writable($this->destinationPath.'/'.$ext))
                $this->setMessage("Destination is not writable !");
            else
            {
                if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.'/'.$ext.'/'.$this->uploadName))
                {
                    $result =   true;
                }
                else
                {
                    $this->setMessage("Upload failed , try later !");
                }
            }
        }
        else
        {
            $this->setMessage("Invalid file format !");
        }
        return $result;
    }

    function deleteUploaded($fileBrowse){
        $name   =   $_FILES[$fileBrowse]["name"];
        $ext    =   pathinfo($name,PATHINFO_EXTENSION);
        unlink($this->destinationPath.'/'.$ext.'/'.$this->uploadName);
    }
}
?>

Upvotes: 3

Kiran
Kiran

Reputation: 921

Here is a new Uploader class Save the following block as Uploader.php

<?php

    class Uploader
    {
        private $destinationPath;
        private $errorMessage;
        private $extensions;
        private $allowAll;
        private $maxSize;
        private $uploadName;
        private $seqnence;
        public $name='Uploader';
        public $useTable    =false;

        function setDir($path){
            $this->destinationPath  =   $path;
            $this->allowAll =   false;
        }

        function allowAllFormats(){
            $this->allowAll =   true;
        }

        function setMaxSize($sizeMB){
            $this->maxSize  =   $sizeMB * (1024*1024);
        }

        function setExtensions($options){
            $this->extensions   =   $options;
        }

        function setSameFileName(){
            $this->sameFileName =   true;
            $this->sameName =   true;
        }
        function getExtension($string){
            $ext    =   "";
            try{
                    $parts  =   explode(".",$string);
                    $ext        =   strtolower($parts[count($parts)-1]);
            }catch(Exception $c){
                    $ext    =   "";
            }
            return $ext;
    }

        function setMessage($message){
            $this->errorMessage =   $message;
        }

        function getMessage(){
            return $this->errorMessage;
        }

        function getUploadName(){
            return $this->uploadName;
        }
        function setSequence($seq){
            $this->imageSeq =   $seq;
    }

    function getRandom(){
        return strtotime(date('Y-m-d H:i:s')).rand(1111,9999).rand(11,99).rand(111,999);
    }
    function sameName($true){
        $this->sameName =   $true;
    }
        function uploadFile($fileBrowse){
            $result =   false;
            $size   =   $_FILES[$fileBrowse]["size"];
            $name   =   $_FILES[$fileBrowse]["name"];
            $ext    =   $this->getExtension($name);
            if(!is_dir($this->destinationPath)){
                $this->setMessage("Destination folder is not a directory ");
            }else if(!is_writable($this->destinationPath)){
                $this->setMessage("Destination is not writable !");
            }else if(empty($name)){
                $this->setMessage("File not selected ");
            }else if($size>$this->maxSize){
                $this->setMessage("Too large file !");
            }else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){

        if($this->sameName==false){
                    $this->uploadName   =  $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
                }else{
            $this->uploadName=  $name;
        }
                if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
                    $result =   true;
                }else{
                    $this->setMessage("Upload failed , try later !");
                }
            }else{
                $this->setMessage("Invalid file format !");
            }
            return $result;
        }

        function deleteUploaded(){
            unlink($this->destinationPath.$this->uploadName);
        }

    }

?>

Now upload files using Uploader class. Use following code . Code block is self explanatory .

<?php

$uploader   =   new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif'));  //allowed extensions list//
$uploader->setMaxSize(.5);                          //set max file size to be allowed in MB//

if($uploader->uploadFile('txtFile')){   //txtFile is the filebrowse element name //     
    $image  =   $uploader->getUploadName(); //get uploaded file name, renames on upload//

}else{//upload failed
    $uploader->getMessage(); //get upload error message 
}


?>

Upvotes: 12

Related Questions