( ′∀`)σ≡σ☆))Д′)レ(゚∀゚;)ヘ=З=З=Зε≡(ノ´_ゝ`)ノ
<?php
// upload_handler.php - Handles image uploads for tools
header('Content-Type: application/json');
// Error handling
ini_set('display_errors', 0);
error_reporting(E_ALL);
function returnError($msg) {
echo json_encode(['success' => false, 'error' => $msg]);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
returnError('Invalid request method');
}
if (!isset($_FILES['file'])) {
returnError('No file uploaded');
}
$file = $_FILES['file'];
// Validate error
if ($file['error'] !== UPLOAD_ERR_OK) {
returnError('Upload failed with error code: ' . $file['error']);
}
// Validate type
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
if (!in_array($mime, $allowedTypes)) {
returnError('Invalid file type. Only JPG, PNG, GIF, and WebP are allowed.');
}
// Validate size (e.g., 5MB)
if ($file['size'] > 5 * 1024 * 1024) {
returnError('File too large. Maximum size is 5MB.');
}
// Generate unique name
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = uniqid('img_', true) . '.' . $ext;
$uploadDir = __DIR__ . '/uploads/';
if (!is_dir($uploadDir)) {
if (!mkdir($uploadDir, 0755, true)) {
returnError('Failed to create upload directory');
}
}
$destPath = $uploadDir . $filename;
if (move_uploaded_file($file['tmp_name'], $destPath)) {
// Construct URL
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST'];
$scriptDir = dirname($_SERVER['SCRIPT_NAME']);
// Ensure no trailing slash in scriptDir
$scriptDir = rtrim($scriptDir, '/\\');
$url = $protocol . $host . $scriptDir . '/uploads/' . $filename;
echo json_encode(['success' => true, 'url' => $url]);
} else {
returnError('Failed to save file');
}