forked from smalos/nuBuilder4-Code-Library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
upload.php
86 lines (73 loc) · 2.19 KB
/
upload.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
<?php
// Upload directory
$uploaddir = './documents/';
//$uploaddir = $_SERVER['DOCUMENT_ROOT']."/documents/";
// Allowed file extensions
$allowed = array(
'pdf',
'docx'
);
// Maximum file size
$maxfilesize = 5 * 1024 * 1024; // (5 MB)
try
{
$data = array();
if (!isset($_FILES['file']) || !is_uploaded_file($_FILES['file']['tmp_name']) || $_FILES['file']['error'] != UPLOAD_ERR_OK)
{
$data['error'] = $_FILES['file']['error'];
}
else
{
$record_id = isset($_POST['record_id']) ? $_POST['record_id'] : "";
$filename = $_FILES["file"]["name"];
$filesize = $_FILES["file"]["size"];
if ($filesize > $maxfilesize)
{
$data['error'] = 'FILE_TOO_LARGE';
}
else
{
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed))
{
$data['error'] = 'INVALID_FILE_TYPE';
}
else
{
$file_name = sanitizeFilename(basename($filename));
// Create a unique file id
$file_id = time() . '_' . uniqid() . '_' . $record_id;
$uploaddir = rtrim($uploaddir, '/') . '/';
$file = $uploaddir . $file_id . '_' . $file_name;
// Create directory if does not exist
if (!is_dir($uploaddir))
{
mkdir($uploaddir, 0755);
}
// Move the file to the destination directory
if (move_uploaded_file($_FILES['file']['tmp_name'], $file))
{
$data['error'] = '';
$data['file_name'] = $file_name;
$data['file_id'] = $file_id;
}
else
{
$data['error'] = 'ERROR_MOVING_FILE';
}
}
}
}
echo json_encode($data);
}
catch(Exception $e)
{
$data['error'] = $e->getMessage();
echo json_encode($data);
}
function sanitizeFilename($file)
{
$file = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).])", '', $file);
return mb_ereg_replace("([\.]{2,})", '', $file);
}
?>