From bbdbc8cbd9142c4377197964d48b2db5dfe00fa3 Mon Sep 17 00:00:00 2001 From: Malf Furious Date: Sun, 16 Apr 2017 03:17:09 -0400 Subject: Add global function saveFile() --- app/class/globals.php | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) (limited to 'app/class') diff --git a/app/class/globals.php b/app/class/globals.php index 5a03da9..615efa6 100644 --- a/app/class/globals.php +++ b/app/class/globals.php @@ -103,4 +103,45 @@ function getErrors(string $level) : array return $_SCROTT[$level]; } +/* + * Save an uploaded file and impose some constraints on supplied + * data. Caller can optionally pass some strings by reference to + * be given the supplied file's original name and mime-type. + * Maxsize is in bytes. If this function returns false, the + * appropriate error will be logged. + */ +function saveFile(array $file, string $path, int $maxsize, ?array $allowedMime = NULL, + ?string &$origName = NULL, ?string &$origMime = NULL) : bool +{ + if ($file['error'] > 0) + { + if ($file['error'] != UPLOAD_ERR_NO_FILE) + logError(ERROR, "An unknown error occurred"); + + return false; + } + + if ($file['size'] > $maxsize) + { + logError(ERROR, "File must be no larger than " . $maxsize . " bytes"); + return false; + } + + if (is_array($allowedMime) && array_search($file['type'], $allowedMime) === false) + { + logError(ERROR, "File type is not supported"); + return false; + } + + if (!move_uploaded_file($file['tmp_name'], $path)) + { + logError(ERROR, "Error saving uploaded file"); + return false; + } + + $origName = $file['name']; + $origMime = $file['type']; + return true; +} + ?> -- cgit v1.2.3