34321-vm/save_audio.php
2025-09-23 21:45:57 +00:00

77 lines
2.9 KiB
PHP

<?php
header('Content-Type: application/json');
$response = [];
// The directory where recordings will be stored.
$uploadDir = 'uploads/';
// Check if the upload directory exists and is writable.
if (!is_dir($uploadDir)) {
// Try to create it if it doesn't exist.
if (!mkdir($uploadDir, 0775, true)) {
$response = ['success' => false, 'error' => 'Server error: Cannot create upload directory.'];
echo json_encode($response);
exit;
}
}
if (!is_writable($uploadDir)) {
$response = ['success' => false, 'error' => 'Server error: The uploads directory is not writable. Please check file permissions.'];
echo json_encode($response);
exit;
}
// Check if a file was uploaded and there are no errors.
if (isset($_FILES['audio_data']) && $_FILES['audio_data']['error'] == UPLOAD_ERR_OK) {
// Get the temporary file path of the uploaded file.
$tmpName = $_FILES['audio_data']['tmp_name'];
// Generate a unique filename to prevent overwriting existing files.
$fileName = 'recording_' . date('Y-m-d_H-i-s') . '_' . uniqid() . '.wav';
$filePath = $uploadDir . $fileName;
// Move the uploaded file from the temporary directory to the final destination.
if (move_uploaded_file($tmpName, $filePath)) {
$response['success'] = true;
$response['message'] = 'Audio saved successfully.';
$response['file_path'] = $filePath;
} else {
$response['success'] = false;
$response['error'] = 'Error saving audio file after upload. Check directory permissions.';
}
} else {
// Handle potential upload errors.
$error_message = 'No audio data received or an upload error occurred.';
if (isset($_FILES['audio_data']['error'])) {
switch ($_FILES['audio_data']['error']) {
case UPLOAD_ERR_INI_SIZE:
$error_message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
break;
case UPLOAD_ERR_FORM_SIZE:
$error_message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
break;
case UPLOAD_ERR_PARTIAL:
$error_message = 'The uploaded file was only partially uploaded.';
break;
case UPLOAD_ERR_NO_FILE:
$error_message = 'No file was uploaded.';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$error_message = 'Missing a temporary folder.';
break;
case UPLOAD_ERR_CANT_WRITE:
$error_message = 'Failed to write file to disk.';
break;
case UPLOAD_ERR_EXTENSION:
$error_message = 'A PHP extension stopped the file upload.';
break;
}
}
$response['success'] = false;
$response['error'] = $error_message;
}
echo json_encode($response);
?>