-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtilFileUpload.php
113 lines (85 loc) · 2.49 KB
/
UtilFileUpload.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/*
* @Author : ndione24
* twitter : @NdioneNdione1
*/
class UtilFileUpload
{
private array $files;
private string $filename = "";
private array $errors = [];
private $maxSize = null;
private string $targetDirectory=""; // default current directory
private ?array $acceptedExtensions = null;
function __construct(array $files)
{
$this->files = $files;
}
public function generateName()
{
$name = basename($this->files["name"]);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$this->filename = uniqid() . "." . $extension;
return $this;
}
public function acceptedExtensions($acceptedExtensions)
{
$this->acceptedExtensions = $acceptedExtensions;
return $this;
}
public function getError()
{
return $this->errors;
}
public function process()
{
// check type
if (!is_null($this->acceptedExtensions)) {
if (!in_array(pathinfo(basename($this->files["name"]), PATHINFO_EXTENSION), $this->acceptedExtensions)) {
$this->errors[] = "file type not accepted";
return;
}
}
if(strlen($this->targetDirectory)==0){
$this->targetDirectory =getcwd();
}
// check size
if (!is_null($this->maxSize)) {
if ($this->files["size"] > $this->maxSize) {
$this->errors[] = "exceeded size limit";
return;
}
}
if ($this->files["error"] == UPLOAD_ERR_OK) {
$tmp_name = $this->files["tmp_name"];
if (strcmp($this->filename, "") == 0) {
$this->filename = $tmp_name;
}
if (!move_uploaded_file($tmp_name, $this->targetDirectory . DIRECTORY_SEPARATOR . $this->filename)) {
echo $this->targetDirectory;
echo "Err ********" . $this->files["error"];
$this->errors[] = "Please check permission of your target Directory";
}
} else {
$this->errors[] = "Error for uploading";
}
}
public function moveTo($directory)
{
$this->targetDirectory = $directory;
return $this;
}
function setName($filename)
{
$this->filename = $filename;
}
function getFilename()
{
return $this->filename;
}
function sizeLimit($maxSize)
{
$this->maxSize = $maxSize;
return $this;
}
}