Skin uploader in php

Oh, how I hate PHP
This commit is contained in:
jkoci 2023-07-10 22:07:20 +02:00
parent cfb957b3e9
commit 31324db80f
4 changed files with 120 additions and 0 deletions

4
skinup/Makefile Normal file
View File

@ -0,0 +1,4 @@
all:
run:
php -c . -S localhost:8080

14
skinup/form.html Normal file
View File

@ -0,0 +1,14 @@
<form class="upload-skin" method="POST" action="target.php" target="_self" enctype="multipart/form-data">
<label for="player-name">Player name</label>
<input type="text" id="player-name" name="player-name" required="required">
Your YL name, with correct capitalization: if your YL name is John, do not write JOHN or john.
<p>
<label for="skin-name">Skin name</label>
<input type="text" id="skin-name" name="skin-name">
If you plan to submit multiple skins, give each a unique name.
<p>
<label for="skin-file">File:</label>
<input type="file" id="skin-file" name="skin-file" required="required">
<p>
<input type="submit" value="Upload">
</form>

1
skinup/php.ini Normal file
View File

@ -0,0 +1 @@
file_uploads = On

101
skinup/target.php Normal file
View File

@ -0,0 +1,101 @@
<pre>
<?php
define("UPLOAD_DIR", realpath("./uploaddest"));
if (!UPLOAD_DIR){
die("UPLOAD_DIR does not exist.");
}
// Oh, how I miss python's pathlib
function get_name($path) {
return pathinfo($path, PATHINFO_FILENAME);
}
function get_dir($path) {
return pathinfo($path, PATHINFO_DIRNAME);
}
function get_ext($path) {
return pathinfo($path, PATHINFO_EXTENSION);
}
// See? So complicated
function with_name($path, $name) {
$ret = "";
if(get_dir($path)) {
$ret = get_dir($path) . DIRECTORY_SEPARATOR;
}
$ret = $ret . $name;
if(get_ext($path)){
$ret = $ret . "." . get_ext($path);
}
return $ret;
}
function with_ext($path, $ext) {
$ret = "";
if(get_dir($path)) {
$ret = get_dir($path) . DIRECTORY_SEPARATOR;
}
$ret = $ret . get_name($path);
if($ext){
$ret = $ret . "." . $ext;
}
return $ret;
}
function with_dir($path, $dir) {
$ret = "";
if($dir){
$ret = $ret . $dir . DIRECTORY_SEPARATOR;
}
$ret = $ret . get_name($path);
if(get_ext($path)){
$ret = $ret . "." . get_ext($path);
}
return $ret;
}
function as_uploaded($fname) {
return with_dir($fname, UPLOAD_DIR);
}
function upload_file($_file, $destname) {
if ($_file["error"] != UPLOAD_ERR_OK) {
return false;
}
if (move_uploaded_file($_file["tmp_name"], as_uploaded($destname))) {
return true;
}
return false;
}
$skin = $_FILES["skin-file"];
$player_name = $_POST["player-name"];
$dest = uniqid($player_name) . "." . get_ext($skin["name"]);
$save_as = $player_name . ($_POST["skin-name"]? "_{$_POST['skin-name']}" : "") . "." . get_ext($skin["name"]);
if (upload_file($skin, $dest)) {
$meta = with_ext(as_uploaded($dest), "json");
file_put_contents($meta, json_encode([
"player-name" => $_POST["player-name"],
"skin-name" => $_POST["skin-name"],
"file-name" => $dest,
"save-as" => $save_as,
]));
echo "Upload OK";
} else {
// I just resign on handling all the errors.
echo "Upload failed";
}
?>
</pre>