From f3e0c1a833fac6982d524df172ee61f220492d42 Mon Sep 17 00:00:00 2001 From: ilotterytea Date: Thu, 20 Mar 2025 02:48:10 +0500 Subject: feat: random file names --- lib/utils.php | 13 +++++++++++++ public/upload.php | 15 +++++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/utils.php b/lib/utils.php index b5f8431..af8cc2f 100644 --- a/lib/utils.php +++ b/lib/utils.php @@ -1,4 +1,6 @@ $message, 'data' => $data ]); +} + +function generate_random_char_sequence(array $chars, int $length): string +{ + $o = ""; + + for ($i = 0; $i < $length; $i++) { + $o .= $chars[random_int(0, count($chars) - 1)]; + } + + return $o; } \ No newline at end of file diff --git a/public/upload.php b/public/upload.php index 2952315..1ca5559 100644 --- a/public/upload.php +++ b/public/upload.php @@ -14,11 +14,22 @@ if (!is_dir(FILE_DIRECTORY) && !mkdir(FILE_DIRECTORY, 0777, true)) { $file = $_FILES['file']; -if (!move_uploaded_file($file['tmp_name'], FILE_DIRECTORY . sprintf('/%s', $file['name']))) { +// checking file mimetype +$finfo = new finfo(FILEINFO_MIME_TYPE); +if (false === $file_ext = array_search($finfo->file($file['tmp_name']), FILE_ACCEPTED_MIME_TYPES, true)) { + json_response(null, 'Invalid file format', 400); + exit(); +} + +$file_id = generate_random_char_sequence(FILE_ID_CHARACTERS, FILE_ID_LENGTH); + +if (!move_uploaded_file($file['tmp_name'], FILE_DIRECTORY . sprintf('/%s.%s', $file_id, $file_ext))) { json_response(null, 'Failed to save the file. Try again later.', 500); exit(); } json_response([ - 'id' => $file['name'] + 'id' => $file_id, + 'ext' => $file_ext, + 'mime' => FILE_ACCEPTED_MIME_TYPES[$file_ext] ], null, 201); \ No newline at end of file -- cgit v1.2.3