UploadFile.php
2.64 KB
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
<?php
require_once("Constants.php");
class UploadManager
{
private $upload_max_size;
private $post_max_size;
private $file;
public function __construct()
{
$this->file = null;
$this->upload_max_size = ini_get('upload_max_filesize');
$this->post_max_size = ini_get('post_max_size');
}
public function run($target_dir)
{
$res = $this->init();
if (!$res["success"])
return $res;
if ( ($error_code = $this->file['error']) != UPLOAD_ERR_OK )
return array(
"success" => false,
"error" => $this->getUploadErrorMessage($error_code)
);
$fileName = $this->file['name'];
$fileTmp = $this->file['tmp_name'];
if( !is_uploaded_file($fileTmp) )
return array(
"success" => false,
"error" => 'Error uploading file - unknown error.'
);
$movedFile = time().'_'.$this->generateRandomString().'_'.basename( $fileName );
$target_path = $target_dir.$movedFile;
if( !move_uploaded_file($fileTmp, $target_path) )
return array(
"success" => false,
"error" => 'Error uploading file - could not save uploaded file - Internal error'
);
return array(
"success" => true,
"fileName" => $movedFile
);
}
private function init()
{
$this->file = null;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && empty($_FILES) && $_SERVER['CONTENT_LENGTH'] > 0)
return array(
"success" => false,
"error" => 'Error uploading file - Posted data is too large (limitation to '.$this->post_max_size.')'
);
if (!isset($_FILES['sourcefile']))
return array(
"success" => false,
"error" => 'Error uploading file - cannot get source file'
);
$this->file = $_FILES['sourcefile'];
return array(
"success" => true
);
}
private function getUploadErrorMessage($error)
{
$message = 'Error uploading file - ';
switch($error)
{
case UPLOAD_ERR_OK:
$message = false;
break;
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
$message .= 'file too large (limitation to '.$this->upload_max_size.')';
break;
case UPLOAD_ERR_PARTIAL:
$message .= 'file upload not completed.';
break;
case UPLOAD_ERR_NO_FILE:
$message .= 'zero-length file uploaded.';
break;
default:
$message .= 'internal error #'.$error;
break;
}
return $message;
}
private function generateRandomString($length = 10)
{
return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
}
}
$upMgr = new UploadManager();
$r = $upMgr->run(TREPS_PHP_TMP_DIR);
echo json_encode($r);
?>