萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 批量刪除實作:核心邏輯、安全防護與前端配合

原始代碼問題分析

<?php
if ($_POST['chk']) {
    $sid = implode(',', $_POST['chk']);
    $query = mysql_query("delete from news where news_id in ($sid)");
    // ...
}

四大風險:

  1. SQL 注入:$_POST['chk'] 未驗證直接拼接,攻擊者可提交 1; DROP TABLE news;--。
  2. 空陣列導致語法錯誤:implode(',', []) 返回空字串,SQL 變為 IN () 報錯。
  3. 使用已棄用 mysql_* 函數:PHP 7.0+ 已移除。
  4. 無 CSRF 保護:惡意頁面可誘導用戶提交刪除請求。

安全標準實作 (PDO + 預處理 + 事務)

<?php
// config.php - 資料庫連接單例
$pdo = new PDO('mysql:host=localhost;dbname=cms;charset=utf8mb4', 'user', 'pass', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
]);

// delete_batch.php
session_start();
header('Content-Type: application/json; charset=utf-8');

try {
    // 1. CSRF 驗證
    if (!hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'] ?? '')) {
        throw new Exception('CSRF token 無效', 403);
    }

    // 2. 獲取並驗證 ID 列表
    $ids = $_POST['ids'] ?? [];
    if (!is_array($ids) || empty($ids)) {
        throw new Exception('未選擇任何項目', 400);
    }

    // 3. 過濾:只保留正整數
    $ids = array_filter($ids, fn($id) => ctype_digit((string)$id));
    $ids = array_map('intval', $ids);
    $ids = array_unique($ids);

    if (empty($ids)) {
        throw new Exception('無效的 ID 列表', 400);
    }

    // 4. 可選:權限檢查 (確認當前用戶有權刪除這些記錄)
    // $allowed = $pdo->query("SELECT news_id FROM news WHERE news_id IN (".implode(',',$ids).") AND author_id={$userId}")->fetchAll(PDO::FETCH_COLUMN);
    // $ids = array_intersect($ids, $allowed);

    // 5. 事務執行批量刪除
    $pdo->beginTransaction();
    
    // 動態生成佔位符: ?,?,?
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $sql = "DELETE FROM news WHERE news_id IN ($placeholders)";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($ids);
    $deleted = $stmt->rowCount();
    
    $pdo->commit();

    echo json_encode([
        'success' => true,
        'deleted' => $deleted,
        'message' => "成功刪除 $deleted 條記錄"
    ]);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    http_response_code($e->getCode() ?: 500);
    error_log("Batch delete error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

前端配合:防誤刪、確認對話框、AJAX 提交

<!-- 列表頁 -->
<form id="batchForm" method="post">
    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] = bin2hex(random_bytes(32)) ?>">
    
    <table>
        <thead>
            <tr><th><input type="checkbox" id="checkAll"></th><th>標題</th><th>操作</th></tr>
        </thead>
        <tbody>
<?php foreach ($news as $item): ?>
            <tr>
                <td><input type="checkbox" name="ids[]" value="<?= $item['news_id'] ?>" class="row-check"></td>
                <td><?= htmlspecialchars($item['title']) ?></td>
                <td><a href="edit.php?id=<?= $item['news_id'] ?>">編輯</a></td>
            </tr>
<?php endforeach; ?>
        </tbody>
    </table>
    
    <button type="button" id="btnBatchDelete" class="btn-danger" disabled>批量刪除 (<span id="selCount">0</span>)</button>
</form>

<script>
const form = document.getElementById('batchForm');
const checkAll = document.getElementById('checkAll');
const rowChecks = document.querySelectorAll('.row-check');
const btnDelete = document.getElementById('btnBatchDelete');
const selCount = document.getElementById('selCount');

function updateUI() {
    const checked = form.querySelectorAll('input[name="ids[]"]:checked');
    const count = checked.length;
    selCount.textContent = count;
    btnDelete.disabled = count === 0;
}

checkAll.addEventListener('change', () => {
    rowChecks.forEach(cb => cb.checked = checkAll.checked);
    updateUI();
});
rowChecks.forEach(cb => cb.addEventListener('change', updateUI));

btnDelete.addEventListener('click', async () => {
    if (!confirm('確定要刪除選中的項目嗎?此操作不可恢復!')) return;
    
    btnDelete.disabled = true;
    btnDelete.textContent = '刪除中...';
    
    const formData = new FormData(form);
    
    try {
        const res = await fetch('delete_batch.php', {method: 'POST', body: formData});
        const data = await res.json();
        
        if (data.success) {
            alert(data.message);
            location.reload(); // 或移除對應 DOM 行
        } else {
            alert('失敗: ' + data.message);
        }
    } catch (e) {
        alert('請求異常: ' + e.message);
    } finally {
        btnDelete.disabled = false;
        btnDelete.innerHTML = '批量刪除 (0)';
        updateUI();
    }
});
</script>

「點取消也能刪除」根因

原代碼無 confirm() 阻斷,且 if($_POST['chk']) 只要陣列非空即執行。瀏覽器原生 confirm() 返回 false 時需阻止表單提交:

<form onsubmit="return confirm('確定刪除?')"> ... </form>
// 或 JS 阻止
form.addEventListener('submit', e => { if(!confirm('...')) e.preventDefault(); });

軟刪除模式 (推薦生產環境)

-- 資料表增加欄位
ALTER TABLE news ADD COLUMN deleted_at DATETIME NULL DEFAULT NULL;
ALTER TABLE news ADD INDEX idx_deleted (deleted_at);

-- 批量軟刪除
UPDATE news SET deleted_at = NOW() WHERE news_id IN (?,?,?) AND deleted_at IS NULL;

-- 查詢時自動排除
SELECT * FROM news WHERE deleted_at IS NULL;
-- 或建立 VIEW
CREATE VIEW news_active AS SELECT * FROM news WHERE deleted_at IS NULL;

優點:資料可恢復、審計追蹤、避免外鍵約束衝突、符合 GDPR 等合規要求。

copyright © 萬盛學電腦網 all rights reserved