summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorilotterytea <iltsu@alright.party>2025-03-20 02:48:10 +0500
committerilotterytea <iltsu@alright.party>2025-03-20 02:48:10 +0500
commitf3e0c1a833fac6982d524df172ee61f220492d42 (patch)
tree5e5f8ba377d3039efee381ad8009b15012fbb1fe
parent66a0a296b6608c30b14d1b8ffa7fa709e806c1ff (diff)
feat: random file names
-rw-r--r--lib/utils.php13
-rw-r--r--public/upload.php15
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 @@
<?php
+include_once $_SERVER['DOCUMENT_ROOT'] . '/../config.php';
+
function json_response(mixed $data, string|null $message, int $code = 200)
{
http_response_code($code);
@@ -8,4 +10,15 @@ function json_response(mixed $data, string|null $message, int $code = 200)
'message' => $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