VvvebJs / upload.php
CatPtain's picture
Upload 9 files
85bc0da verified
<?php
/*
Copyright 2017 Ziadin Givan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
https://github.com/givanz/VvvebJs
*/
/*
This script is used by image upload input to save the image on the server and return the image url to be set as image src attribute.
*/
// Include authentication and storage
require_once __DIR__ . '/save.php';
// Check if user is authenticated
if (!isset($_SESSION['user_id'])) {
http_response_code(401);
echo json_encode([
'success' => false,
'message' => 'Authentication required'
]);
exit;
}
$userId = $_SESSION['user_id'];
if ($_FILES && $_FILES['file']) {
$file = $_FILES['file'];
// Validate file
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
if (!in_array($file['type'], $allowedTypes)) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => 'Invalid file type. Allowed: JPEG, PNG, GIF, WebP, SVG'
]);
exit;
}
$maxSize = 5 * 1024 * 1024; // 5MB
if ($file['size'] > $maxSize) {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => 'File too large. Maximum size: 5MB'
]);
exit;
}
// Generate unique filename with user prefix
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$timestamp = date('Y-m-d_H-i-s');
$filename = 'media/' . $userId . '_' . $timestamp . '_' . uniqid() . '.' . $extension;
// Create user-specific media directory
$userMediaDir = __DIR__ . '/user-files/' . $userId . '/media/';
if (!is_dir($userMediaDir)) {
mkdir($userMediaDir, 0777, true);
}
$localPath = $userMediaDir . basename($filename);
if (move_uploaded_file($file['tmp_name'], $localPath)) {
// Save to user's storage as well
$fileContent = file_get_contents($localPath);
$storageManager->saveFile($filename, $fileContent);
// Return relative path for use in editor
$relativePath = 'user-files/' . $userId . '/media/' . basename($filename);
echo json_encode([
'success' => true,
'url' => $relativePath,
'filename' => basename($filename),
'size' => $file['size'],
'type' => $file['type'],
'message' => 'File uploaded successfully'
]);
} else {
http_response_code(500);
echo json_encode([
'success' => false,
'message' => 'Failed to upload file'
]);
}
} else {
http_response_code(400);
echo json_encode([
'success' => false,
'message' => 'No file uploaded'
]);
}