-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload-basic.php
More file actions
149 lines (129 loc) · 5.63 KB
/
upload-basic.php
File metadata and controls
149 lines (129 loc) · 5.63 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
<?php
// error_reporting(E_ALL);
//////////////////////////////////////////
////////// custom variables //////////////
include_once(__DIR__."/.chunk_custom.inc.php");
//////////////////////////////////////////
////////// common stuff //////////////
$customSubFolder = "";
$targetPath = join(DIRECTORY_SEPARATOR, array(__DIR__, "uploads"));
$logName = pathinfo(__FILE__, PATHINFO_FILENAME);
$logfile = $logName . '.log';
// we can't tell if behind a proxy or if any of these are set
$keys = ['REMOTE_ADDR','HTTP_X_FORWARDED_FOR','HTTP_CF_CONNECTING_IP','HTTP_X_REAL_IP'];
foreach ($keys as $key) { $remote_addr = isset($_SERVER[$key]) ? $_SERVER[$key] : $remote_addr;}
$remote_country = isset($_SERVER["HTTP_CF_IPCOUNTRY"]) ? $_SERVER["HTTP_CF_IPCOUNTRY"] : '??';
function logger($message='') {
global $logfile, $remote_country, $remote_addr, $logName;
file_put_contents($logfile, sprintf("%s %s [%-15s] %s: %s".PHP_EOL, date("Y-m-d H:i:s"), $remote_country, $remote_addr, $logName, $message), FILE_APPEND);
}
/////////////////////////////////////
// ========================================
// DEPENDENCY FUNCTIONS
// ========================================
$upload_max_filesize = ini_get('post_max_size');
$phpFileUploadErrors = array(
0 => 'success',
1 => "ERROR: The uploaded file exceeds the upload_max_filesize={$upload_max_filesize} in php.ini",
2 => 'ERROR: The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'ERROR: The uploaded file was only partially uploaded',
4 => 'ERROR: No file was uploaded',
6 => 'ERROR: Missing a temporary folder',
7 => 'ERROR: Failed to write file to disk.',
8 => 'ERROR: A PHP extension stopped the file upload.',
);
function joinPaths(string|array|null ...$paths): string
{
$flatPaths = [];
array_walk_recursive($paths, function ($p) use (&$flatPaths) { $flatPaths[] = $p; });
$paths = array_filter($flatPaths, fn ($p) => '' !== $p && null !== $p);
return preg_replace('+/{2,}+', DIRECTORY_SEPARATOR, implode(DIRECTORY_SEPARATOR, $paths));
}
function getTargetPath($customFiles, $targetBasename, $targetPath) {
$subFolder = '';
$fileExt = pathinfo($targetBasename, PATHINFO_EXTENSION);
// Custom special case just for you: next step is to load the dict off a json file and have various subdirectories+fileLists
foreach($customFiles as $customSubFolder => $arrCutomTypes) {
if (array_key_exists("filename", $arrCutomTypes)) {
if (in_array($targetBasename, $arrCutomTypes["filename"])) {
$subFolder = $customSubFolder;
$targetPath = joinPaths(array($targetPath , $customSubFolder) );
}
}
if (array_key_exists("extension", $arrCutomTypes)) {
if (in_array($fileExt, $arrCutomTypes["extension"])) {
$subFolder = joinPaths(array($customSubFolder, date("Y-m-d")));
$targetPath = joinPaths(array($targetPath , $subFolder));
mkdir($targetPath, 0644);
}
}
}
return array("subFolder" => $subFolder, "targetPath" => $targetPath);
}
// ========================================
// ARGUMENTS
// ========================================
$required_FILES = array('name', 'full_path', 'type', 'tmp_name', 'error', 'size');
logger(json_encode($_FILES)); // {"file":{"name":"filename.ext","full_path":"filename.ext","type":"image\/jpeg","tmp_name":"\/tmp\/phpcfldoh9n05o1aoFpDDk","error":0,"size":661355}}
if (!isset($_FILES)) {
logger("ERROR: _FILES unset");
die();
} elseif (!isset($_FILES['file'])) {
logger("ERROR: _FILES[file] missing");
die();
} else {
logger("_FILES=".json_encode($_FILES));
$missing_FILES = array_diff_key(array_flip($required_FILES), $_FILES['file']);
if ($missing_FILES) {
logger("ERROR: _FILES missing keys:".join(",",$missing_FILES));
die();
}
$fileSize = $_FILES['file']['size'];
$tmp_name = $_FILES['file']['tmp_name'];
$error = $_FILES['file']['error'];
}
$baseName = pathinfo($_FILES['file']["name"], PATHINFO_BASENAME);
$fileName = pathinfo($_FILES['file']["name"], PATHINFO_FILENAME);
$fileExt = pathinfo($_FILES['file']["name"], PATHINFO_EXTENSION);
// https://www.php.net/manual/en/features.file-upload.post-method.php
// Remove anything which isn't a word, whitespace, number, or any of the following caracters: "-_~[]()."
$baseName = mb_ereg_replace("([^\w\s\d\-_~\,\;\[\]\(\)\.])", '-', $baseName);
// Remove any runs of periods
$baseName = mb_ereg_replace("([\.]{2,})", '', $baseName);
// Remove anything which isn't a word, whitespace, number, or any of the following caracters: "-_~[]()"
$fileExt = mb_ereg_replace("([^\w\s\d\-_~\,\;\[\]\(\)])", '', $fileExt);
$targetPaths = getTargetPath($customFiles, $baseName, $targetPath);
$targetFile = join(DIRECTORY_SEPARATOR, array($targetPaths['targetPath'], $baseName));
logger("baseName={$baseName} targetFile={$targetFile} error={$error}");
// ========================================
// VALIDATION CHECKS
// ========================================
// blah, blah, blah validation stuff goes here
// if ($fileSize == 0) $returnResponse("targetChunk size = 0:", $targetChunk);
// $fileSize =0;
if ($error != UPLOAD_ERR_OK) {
logger("{$phpFileUploadErrors[$error]}");
die();
}
if ($fileSize == 0) {
logger("ERROR: _FILES['file']['size'] = 0");
die();
}
if (!$tmp_name) {
logger("ERROR: _FILES['file']['tmp_name'] empty");
die();
}
if (!filesize($tmp_name)) {
logger("ERROR: {$tmp_name} is empty");
die();
}
// ========================================
// MAIN
// ========================================
print '<pre>';
if (move_uploaded_file($tmp_name, $targetFile)) {
print "{$baseName} is valid, and was successfully uploaded.\n";
} else {
print "Possible file upload attack!\n";
}
print "</pre>";