Last active
May 2, 2024 06:51
-
-
Save GitHub30/d6960b85c73e6e5f20386fa665873183 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
function sanitize($filename) | |
{ | |
$text = 'txt|md|rtf|xml|html|css|js|json|csv|sql|log|sh|cer|rss'; | |
$image = 'jpg|jpeg|png|gif|svg|ico|webp|bmp|avif|apng|ai|psd'; | |
$audio = 'mp3|wav|ogg|aac'; | |
$video = 'mp4|mkv|avi|webm|mov|wmv|flv'; | |
$archive = 'zip|gz|7z|rar|apk|jar'; | |
$other = 'pdf|docx|xlsx|pptx|iso|db|ttf|otf|tmp'; | |
$allowed_extensions = "$text|$image|$audio|$video|$archive|$other"; | |
// basename() may prevent filesystem traversal attacks | |
$filename = basename($filename); | |
if (preg_match("/\.($allowed_extensions)$/i", $filename)) { | |
return $filename; | |
} | |
return uniqid(); | |
} | |
function file_put($to, $from = null) | |
{ | |
$to = sanitize($to); | |
if (isset($_GET['folder'])) { | |
$folder = $_GET['folder'] ?: uniqid(); | |
if (!is_dir($folder)) mkdir($folder); | |
$to = "$folder/$to"; | |
} | |
if (is_null($from)) { | |
copy('php://input', $to); | |
} else { | |
move_uploaded_file($from, $to); | |
} | |
echo '<a href="' . $to . '">' . $to . '</a><br/>' . PHP_EOL; | |
} | |
header("Access-Control-Allow-Origin: *"); | |
header("Access-Control-Allow-Methods: *"); | |
header("Access-Control-Allow-Headers: *"); | |
header("Access-Control-Expose-Headers: *"); | |
header("Access-Control-Allow-Credentials: true"); | |
header("Access-Control-Max-Age: 86400"); | |
if ($_FILES) { | |
foreach ($_FILES as $file) { | |
if (is_array($file["error"])) { | |
foreach ($file["error"] as $i => $error) { | |
if ($error === UPLOAD_ERR_OK) { | |
file_put($file["name"][$i], $file["tmp_name"][$i]); | |
} | |
} | |
} else { | |
if ($file["error"] === UPLOAD_ERR_OK) { | |
file_put($file["name"], $file["tmp_name"]); | |
} | |
} | |
} | |
} elseif (in_array($_SERVER["REQUEST_METHOD"], ["POST", "PUT"])) { | |
file_put($_GET["name"] ?? null); | |
} elseif ($_SERVER["REQUEST_METHOD"] === 'GET') { | |
echo '<form method=post enctype=multipart/form-data><input type=file name=files[] multiple onchange=this.form.submit()></form>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment