You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数据库文件重命名返回JSON结果;图片上传至数据库重命名返回JSON新名称

Solution for Database File Rename & Image Upload with JSON Responses

I'll walk you through implementing both of your requested features in PHP, with proper JSON responses and best practices.


1. Database File Rename Function (with JSON Output)

If you're looking to rename an actual database file (e.g., a SQLite .db file—note: avoid renaming MySQL data files while the server is running), here's a robust function that handles the operation and returns a JSON-formatted result:

<?php
function renameDatabaseFile(string $oldFilePath, string $newFilePath): void {
    $response = [];

    // Check if the original file exists
    if (!file_exists($oldFilePath)) {
        $response = [
            'status' => 'error',
            'message' => 'Target database file does not exist',
            'old_filename' => basename($oldFilePath)
        ];
    } 
    // Attempt to rename the file
    elseif (rename($oldFilePath, $newFilePath)) {
        $response = [
            'status' => 'success',
            'message' => 'Database file renamed successfully',
            'old_filename' => basename($oldFilePath),
            'new_filename' => basename($newFilePath)
        ];
    } 
    else {
        $response = [
            'status' => 'error',
            'message' => 'Failed to rename database file: ' . error_get_last()['message'],
            'old_filename' => basename($oldFilePath)
        ];
    }

    // Send JSON response
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

// Example usage (uncomment to test)
// renameDatabaseFile('./data/old_db.db', './data/new_db_v2.db');
?>

Key Notes:

  • Always verify the file exists before attempting a rename to avoid silent failures.
  • The error_get_last() function captures specific errors if the rename fails (e.g., permission issues).
  • We set the Content-Type header to application/json to ensure the response is properly interpreted by clients.

2. Image Upload to Database (with Renaming & JSON Response)

Your existing code saves images to a server directory, but we'll modify it to store the image directly in a database (using MySQL as an example) and generate a unique filename for each upload. First, create a table to store the images:

CREATE TABLE uploaded_images (
    id INT AUTO_INCREMENT PRIMARY KEY,
    filename VARCHAR(255) NOT NULL UNIQUE,
    file_type VARCHAR(100) NOT NULL,
    file_data LONGBLOB NOT NULL,
    uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Now, here's the updated PHP code that handles upload, renaming, database insertion, and JSON responses:

<?php
// Database configuration
$dbHost = 'localhost';
$dbName = 'your_database_name';
$dbUser = 'your_db_username';
$dbPass = 'your_db_password';

if (isset($_POST['upload_Btn'])) {
    $uploadedFile = $_FILES['gambar'];
    $response = [];

    // Validate file is an image
    $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (!in_array($uploadedFile['type'], $allowedMimeTypes)) {
        $response = [
            'status' => 'error',
            'message' => 'Invalid file type. Only JPG, PNG, GIF, and WebP are allowed.'
        ];
        sendJsonResponse($response);
    }

    // Generate a unique new filename
    $fileExt = pathinfo($uploadedFile['name'], PATHINFO_EXTENSION);
    $newFilename = uniqid('uploaded_img_', true) . '.' . strtolower($fileExt);

    try {
        // Read image content
        $fileData = file_get_contents($uploadedFile['tmp_name']);

        // Connect to database (using PDO for security)
        $pdo = new PDO(
            "mysql:host=$dbHost;dbname=$dbName;charset=utf8mb4",
            $dbUser,
            $dbPass,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
        );

        // Insert image into database
        $stmt = $pdo->prepare("
            INSERT INTO uploaded_images (filename, file_type, file_data)
            VALUES (:filename, :file_type, :file_data)
        ");
        $stmt->bindParam(':filename', $newFilename);
        $stmt->bindParam(':file_type', $uploadedFile['type']);
        $stmt->bindParam(':file_data', $fileData, PDO::PARAM_LOB);

        if ($stmt->execute()) {
            $response = [
                'status' => 'success',
                'message' => 'Image uploaded to database successfully',
                'new_filename' => $newFilename
            ];
        } else {
            $response = ['status' => 'error', 'message' => 'Failed to save image to database'];
        }
    } catch (PDOException $e) {
        $response = [
            'status' => 'error',
            'message' => 'Database error: ' . $e->getMessage()
        ];
    } catch (Exception $e) {
        $response = [
            'status' => 'error',
            'message' => 'File read error: ' . $e->getMessage()
        ];
    }

    sendJsonResponse($response);
}

// Helper function to send JSON responses
function sendJsonResponse(array $response): void {
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}
?>

Key Improvements & Notes:

  • Security: Uses PDO prepared statements to prevent SQL injection, which is critical when handling user-uploaded data.
  • Unique Filenames: uniqid('uploaded_img_', true) generates a highly unique filename (includes microtime) to avoid conflicts.
  • Validation: Checks for allowed image MIME types to prevent malicious file uploads.
  • Error Handling: Catches database and file read errors to provide meaningful feedback in the JSON response.
  • Reusability: The sendJsonResponse helper function avoids code duplication for returning JSON.

内容的提问来源于stack exchange,提问作者quentino97

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:37:48