[go: up one dir, main page]

0% found this document useful (0 votes)
6 views2 pages

uploadphp

This PHP script handles file uploads, specifically for GLB files, with a maximum size limit of 50MB. It validates the upload by checking for errors, file type, and size, and creates an 'uploads' directory if it doesn't exist. Upon successful upload, it generates a safe filename and returns a JSON response with the file URL or an error message if any validation fails.

Uploaded by

lahkarj14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

uploadphp

This PHP script handles file uploads, specifically for GLB files, with a maximum size limit of 50MB. It validates the upload by checking for errors, file type, and size, and creates an 'uploads' directory if it doesn't exist. Upon successful upload, it generates a safe filename and returns a JSON response with the file URL or an error message if any validation fails.

Uploaded by

lahkarj14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

<?

php
header('Content-Type: application/json');

// 1. Configure uploads
$targetDir = __DIR__ . '/uploads/';
$maxFileSize = 50 * 1024 * 1024; // 50MB
$allowedTypes = ['model/gltf-binary', 'application/octet-stream'];

// 2. Create uploads folder if missing


if (!file_exists($targetDir)) {
mkdir($targetDir, 0755, true);
}

try {
// 3. Validate upload
if (!isset($_FILES['model'])) {
throw new Exception('No file uploaded');
}

$file = $_FILES['model'];

// 4. Check for errors


if ($file['error'] !== UPLOAD_ERR_OK) {
throw new Exception('Upload error code: ' . $file['error']);
}

// 5. Validate file type


$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

if (!in_array($mimeType, $allowedTypes)) {
throw new Exception('Only GLB files are allowed');
}

// 6. Validate size
if ($file['size'] > $maxFileSize) {
throw new Exception('File exceeds 50MB limit');
}

// 7. Generate safe filename


$originalName = basename($file['name']);
$safeName = preg_replace('/[^a-z0-9\._-]/i', '_', $originalName);
$targetPath = $targetDir . uniqid() . '_' . $safeName;

// 8. Move the file


if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
throw new Exception('Failed to save file');
}

// 9. Return success
echo json_encode([
'success' => true,
'fileUrl' => '/uploads/' . basename($targetPath)
]);

} catch (Exception $e) {


echo json_encode([
'success' => false,
'error' => $e->getMessage()
]);
}

You might also like