File Manager V1.5
FILE_CONTENT: upload_document.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS');
header('Access-Control-Allow-Headers: Authorization, Content-Type, Accept, X-Requested-With, User-Agent, Origin');
header('Access-Control-Max-Age: 86400');
header('Content-Type: application/json; charset=UTF-8');
require_once 'config.php';
require_once 'jwt_helper.php';
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit();
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit();
}
try {
$headers = getallheaders();
$token = null;
if (isset($headers['Authorization'])) {
$auth_header = $headers['Authorization'];
if (preg_match('/Bearer\s(\S+)/', $auth_header, $matches)) {
$token = $matches[1];
}
}
if (!$token) {
throw new Exception('No token provided');
}
$decoded = JWT::decode($token, JWT_SECRET_KEY, array('HS256'));
$user_id = $decoded->user_id;
$user_type = $decoded->user_type;
if ($user_type !== 1) {
if (!isset($_POST['car_id'])) {
throw new Exception('Car ID is required for non-admin users');
}
$stmt = $pdo->prepare("SELECT user_id FROM car_listings WHERE id = ?");
$stmt->execute([$_POST['car_id']]);
$car = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$car || $car['user_id'] != $user_id) {
throw new Exception('Unauthorized access');
}
}
if (!isset($_FILES['document'])) {
throw new Exception('No document file provided');
}
$file = $_FILES['document'];
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new Exception('File upload error: ' . $file['error']);
}
$allowed_types = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
if (!in_array($file['type'], $allowed_types)) {
throw new Exception('Invalid file type. Only PDF and Word documents are allowed.');
}
$upload_dir = 'uploads/documents/';
if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0777, true);
}
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = uniqid() . '_' . $user_id . '.' . $extension;
$filepath = $upload_dir . $filename;
if (!move_uploaded_file($file['tmp_name'], $filepath)) {
throw new Exception('Failed to move uploaded file');
}
$file_url = 'http://' . $_SERVER['HTTP_HOST'] . '/uploads/' . $filepath;
echo json_encode(['url' => $file_url]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
?> [ KEMBALI ]