Created
May 15, 2024 19:41
-
-
Save eskimo/95956baf99c0f5c9bce99f8187f0b02e to your computer and use it in GitHub Desktop.
Igloo - Custom uploader example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
set_time_limit(0); | |
// CONFIGURATION | |
$maxFileSize = 25600000; // 25MB | |
$uploadDirectory = "uploads/"; | |
$allowedTypes = ["image", "video", "audio"]; // USE [] TO ALLOW ALL FILE TYPES | |
$authTokens = ["randomtokenhere", "andanotherone"]; | |
$idLength = 32; | |
// DO NOT EDIT BELOW THIS LINE | |
$headers = getallheaders(); | |
$authBearer = isset($headers["Authorization"]) ? $headers["Authorization"] : null; | |
if (!$authBearer) { | |
error("No authorization header"); | |
} | |
$authToken = explode(" ", $authBearer)[1]; | |
if (!in_array($authToken, $authTokens)) { | |
error("Invalid authorization token"); | |
} | |
if (!isset($_FILES["file"])) { | |
error("No file uploaded"); | |
} | |
$tmp = $_FILES["file"]["tmp_name"]; | |
$fileSize = filesize($tmp); | |
$fileType = explode("/", mime_content_type($tmp))[0]; | |
$fileName = $_FILES["file"]["name"]; | |
$fileExt = pathinfo($fileName, PATHINFO_EXTENSION); | |
if ($fileSize > $maxFileSize) { | |
error("File is too large"); | |
} | |
if (count($allowedTypes) > 0 && !in_array($fileType, $allowedTypes)) { | |
error("File type not allowed"); | |
} | |
$randomName = generateId($idLength).".".$fileExt; | |
$destination = $uploadDirectory.$randomName; | |
if (!move_uploaded_file($tmp, $destination)) { | |
error("Failed to move file"); | |
} | |
if (!file_exists($destination)) { | |
error("File does not exist after move"); | |
} | |
else { | |
$host = $_SERVER["HTTP_HOST"]; | |
$url = "https://".$host."/".$uploadDirectory.$randomName; | |
success($url); | |
} | |
function success($url) { | |
die($url); | |
} | |
function error($message) { | |
die(json_encode([ | |
"error" => $message | |
])); | |
} | |
function generateId($length) { | |
$allowedChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"; | |
$output = ""; | |
for ($i = 0; $i < $length; $i++) { | |
$output .= $allowedChars[random_int(0, strlen($allowedChars) - 1)]; | |
} | |
return $output; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This isn't really secure, should only be used for yourself and people you trust. There's no validation done on any uploads, so someone could easily backdoor with this if you give them access.