php class file upload

Solutions on MaxInterview for php class file upload by the best coders in the world

showing results for - "php class file upload"
Sara
12 May 2017
1<?php
2class Uploader
3{
4    private $destinationPath;
5    private $errorMessage;
6    private $extensions;
7    private $maxSize;
8    private $uploadName;
9    public $name='Uploader';
10
11    function setDir($path){
12        $this->destinationPath  =   $path;
13    }
14
15    function setMaxSize($sizeMB){
16        $this->maxSize  =   $sizeMB * (1024*1024);
17    }
18
19    function setExtensions($options){
20        $this->extensions   =   $options;
21    }
22
23    function setMessage($message){
24        $this->errorMessage =   $message;
25    }
26
27    function getMessage(){
28        return $this->errorMessage;
29    }
30
31    function getUploadName(){
32        return $this->uploadName;
33    }
34
35    function uploadFile($fileBrowse){
36        $result =   false;
37        $size   =   $_FILES[$fileBrowse]["size"];
38        $name   =   $_FILES[$fileBrowse]["name"];
39        $ext    =   pathinfo($name,PATHINFO_EXTENSION);
40
41        $this->uploadName=  $name;
42
43        if(empty($name))
44        {
45            $this->setMessage("File not selected ");
46        }
47        else if($size>$this->maxSize)
48        {
49            $this->setMessage("Too large file !");
50        }
51        else if(in_array($ext,$this->extensions))
52        {
53            if(!is_dir($this->destinationPath))
54                mkdir($this->destinationPath);
55            if(!is_dir($this->destinationPath.'/'.$ext))
56                mkdir($this->destinationPath.'/'.$ext);
57
58            if(file_exists($this->destinationPath.'/'.$ext.'/'.$this->uploadName))
59                $this->setMessage("File already exists. !");
60            else if(!is_writable($this->destinationPath.'/'.$ext))
61                $this->setMessage("Destination is not writable !");
62            else
63            {
64                if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.'/'.$ext.'/'.$this->uploadName))
65                {
66                    $result =   true;
67                }
68                else
69                {
70                    $this->setMessage("Upload failed , try later !");
71                }
72            }
73        }
74        else
75        {
76            $this->setMessage("Invalid file format !");
77        }
78        return $result;
79    }
80
81    function deleteUploaded($fileBrowse){
82        $name   =   $_FILES[$fileBrowse]["name"];
83        $ext    =   pathinfo($name,PATHINFO_EXTENSION);
84        unlink($this->destinationPath.'/'.$ext.'/'.$this->uploadName);
85    }
86}
87?>