<?php
$target_dir = "/var/www/tr143/upload/";

$timestamp = date("dmYHis");

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    // Handle POST request
    $original_filename = $_FILES["file"]["name"];
    $extension = pathinfo($original_filename, PATHINFO_EXTENSION);
    $new_filename = $timestamp . '_' . $original_filename;
    $target_file = $target_dir . $new_filename;

    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "O arquivo " . $new_filename . " foi enviado.";
    } else {
        echo "Houve um erro no upload do arquivo.";
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    // Handle PUT request
    $input = fopen("php://input", "r");
    $original_filename = basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
    $extension = pathinfo($original_filename, PATHINFO_EXTENSION);
    $new_filename = $timestamp . '_' . $original_filename;
    $target_file = $target_dir . $new_filename;
    $target = fopen($target_file, "w");

    if ($input && $target) {
        while ($data = fread($input, 1024)) {
            fwrite($target, $data);
        }
        fclose($input);
        fclose($target);
        echo "O arquivo " . $new_filename . " foi enviado.";
    } else {
        echo "Houve um erro no upload do arquivo.";
    }
} else {
    echo "Método de solicitação não suportado.";
}
?>
