FabrikaHradekTour/res/forum/api/upload_picture.php

71 lines
1.6 KiB
PHP

<?php
include("../../global.php");
session_start();
if (!isset($_SESSION["username"])) goto fail;
$out = $database -> query("SELECT username, admin, id FROM user WHERE BINARY username=\"" . $_SESSION["username"] . "\"");
if ($out -> num_rows != 1)
{
fail:
echo "nope";
header("Location: ../../../index.php");
return;
}
$status = 0;
$supported_formats = array("jpg", "jpeg", "png", "webp");
if (!isset($_FILES["file_upload"]))
{
$status = 1;
goto send;
}
if (!isset($_POST["name"]))
{
$status = 2;
goto send;
}
$file_format = strtolower(pathinfo($_FILES["file_upload"]["name"], PATHINFO_EXTENSION));
if (!in_array($file_format, $supported_formats))
{
$status = 3;
goto send;
}
$res = $out -> fetch_assoc();
if (!$res["admin"])
{
if ($_FILES["file_upload"]["size"] > 5 * 1024 * 1024)
{
$status = 4;
goto send;
}
}
$user_id = $res["id"];
$dir = "../../../user_content/" . $user_id;
if (!(file_exists($dir) && is_dir($dir)))
{
mkdir($dir);
}
$safe_name = mysqli_real_escape_string($database, $_POST["name"]);
$safe_desc = isset($_POST["desc"]) ? mysqli_real_escape_string($database, $_POST["desc"]) : null;
$photo_id = count(glob($dir . "/*")) . "." . $file_format;
$database -> query("INSERT INTO post (title, description, author, photo_id) VALUES (\"" . $safe_name . "\", " . ($safe_desc == null ? "NULL" : "\"" . $safe_desc . "\"") . ", " . $user_id . ", \"" . $photo_id . "\")");
move_uploaded_file($_FILES["file_upload"]["tmp_name"], $dir . "/" . $photo_id);
send:
header('Content-type: application/json');
echo json_encode(["status" => $status]);