upload_logo.php

1.24 KB
02/11/2025 07:33
PHP
upload_logo.php
<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

// Accepts multipart/form-data with field 'file'. Saves to api/storage/ and returns relative path.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Method not allowed']);
    exit;
}

if (empty($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['ok' => false, 'error' => 'No file uploaded or upload error']);
    exit;
}

$file = $_FILES['file'];
$tmp = $file['tmp_name'];
$name = $file['name'];

$ext = pathinfo($name, PATHINFO_EXTENSION);
$ext = strtolower($ext);
$allowed = ['png', 'jpg', 'jpeg', 'gif', 'webp'];
if (!in_array($ext, $allowed)) {
    echo json_encode(['ok' => false, 'error' => 'Invalid file type']);
    exit;
}
/*
// disable file upload in demo
$dir = __DIR__.'/storage';
if (!is_dir($dir)) {
@mkdir($dir, 0755, true);
}

$basename = 'logo.png';
$path = $dir.'/'.$basename;

if (!move_uploaded_file($tmp, $path)) {
echo json_encode(['ok' => false, 'error' => 'Could not move uploaded file']);
exit;
}
 */
// Return path relative to web root
$relative = 'api/storage/'.$basename;
echo json_encode(['ok' => true, 'url' => $relative]);