PHP 批量刪除操作實用示例
操作日誌:";print_r($deleter->getLog());## 5. 實際應用場景示例### 5.1 清理用戶上傳的臨時圖片```php// 刪除7天前的臨時圖片(jpg/png)$pattern = 'uploads/temp/*.{jpg,png}';$files = glob($pattern, GLOB_BRACE);$sevenDaysAgo = strtotime('-7 days');$deleted = 0;foreach ($files as $file) {if (filemtime($file) < $sevenDaysAgo) {if (unlink($file)) {$deleted++;echo "已清理 {$deleted} 張過期臨時圖片";### 5.2 批量刪除數據庫中的垃圾數據```php// 刪除所有未激活且超過30天的用戶賬號$pdo = new PDO('mysql:host=localhost;dbname=myapp', 'user', 'pass');$query = "DELETE FROM usersWHERE activated = 0AND created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)LIMIT 1000";$totalDeleted = 0;do {$deleted = $pdo->exec($query);$totalDeleted += $deleted;sleep(1); // 避免服務器負載過高} while ($deleted > 0);echo "共刪除 {$totalDeleted} 條過期未激活賬號";## 重要安全提示1. **始終備份重要數據**:執行批量刪除前確保有備份2. **限制刪除範圍**:使用LIMIT分批次處理3. **添加確認步驟**:特別是Web界面中的批量刪除4. **記錄操作日誌**:記錄誰在什麼時候刪除了什麼5. **權限控制**:確保只有授權用戶能執行批量刪除```php// 安全刪除示例:需要確認和權限檢查if ($_SERVER['REQUEST_METHOD'] === 'POST'&& isset($_POST['confirm'])&& $_POST['confirm'] === 'DELETE'&& checkUserPermission('batch_delete')) {// 執行安全的批量刪除操作$result = performSafeBatchDelete();// 記錄操作日誌logAction($_SESSION['user_id'], 'batch_delete', $result);以上示例提供了多種批量刪除的實現方式,您可以根據具體需求選擇合適的方案,並務必添加適當的安全措施。
# PHP 批量刪除操作實用示例以下是幾種常見的批量刪除場景和實現方法,包含詳細的代碼示例和說明:## 1. 批量刪除文件### 1.1 刪除指定目錄下所有文件function deleteAllFiles($dirPath) {if (!is_dir($dirPath)) {throw new InvalidArgumentException("$dirPath 必須是目錄");}$files = glob($dirPath . '*');foreach ($files as $file) {if (is_file($file)) {unlink($file);}}return count($files);}// 使用示例$deletedCount = deleteAllFiles('temp/');echo "已刪除 {$deletedCount} 個文件";```### 1.2 刪除符合特定條件的文件(如過期文件)```phpfunction deleteExpiredFiles($dirPath, $days = 30) {$expiryTime = time() - ($days * 24 * 60 * 60);$deletedCount = 0;foreach (new DirectoryIterator($dirPath) as $fileInfo) {if ($fileInfo->isFile() && $fileInfo->getMTime() < $expiryTime) {unlink($fileInfo->getPathname());$deletedCount++;}}return $deletedCount;}// 刪除60天未修改的文件$count = deleteExpiredFiles('logs/', 60);echo "已刪除 {$count} 個過期日誌文件";```## 2. 批量刪除數據庫記錄### 2.1 使用IN語句批量刪除```phpfunction deleteMultipleRecords(PDO $pdo, $table, array $ids) {if (empty($ids)) return 0;$placeholders = implode(',', array_fill(0, count($ids), '?'));$sql = "DELETE FROM {$table} WHERE id IN ({$placeholders})";$stmt = $pdo->prepare($sql);$stmt->execute($ids);return $stmt->rowCount();}// 使用示例$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');$deletedRows = deleteMultipleRecords($pdo, 'users', [3, 7, 15]);echo "已刪除 {$deletedRows} 條記錄";```### 2.2 分批次刪除大量數據(避免鎖表)```phpfunction batchDelete(PDO $pdo, $table, $condition, $batchSize = 1000) {$totalDeleted = 0;do {$sql = "DELETE FROM {$table} WHERE {$condition} LIMIT {$batchSize}";$deleted = $pdo->exec($sql);$totalDeleted += $deleted;// 如果數據庫支持,可以添加短暫延遲usleep(100000); // 0.1秒} while ($deleted > 0);return $totalDeleted;}// 使用示例:刪除3個月前的不活躍用戶$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');$condition = "last_login < DATE_SUB(NOW(), INTERVAL 3 MONTH)";$total = batchDelete($pdo, 'users', $condition);echo "共刪除 {$total} 條不活躍用戶記錄";```## 3. 批量刪除數組元素```phpfunction removeElements(array &$array, callable $condition) {$removedCount = 0;foreach ($array as $key => $value) {if ($condition($value, $key)) {unset($array[$key]);$removedCount++;}}// 可選:重新索引數字鍵數組if (array_is_list($array)) {$array = array_values($array);}return $removedCount;}// 使用示例:刪除所有空值$data = ['a' => 1, 'b' => null, 'c' => '', 'd' => 2];$removed = removeElements($data, fn($item) => empty($item) && $item !== 0);print_r($data); // 輸出: ['a' => 1, 'd' => 2]echo "移除了 {$removed} 個元素";```## 4. 安全增強版批量刪除類```phpclass BatchDeleter {private $log = [];public function deleteFilesByPattern($pattern, $maxFiles = 1000) {$files = glob($pattern);$deleted = 0;foreach (array_slice($files, 0, $maxFiles) as $file) {if (!is_writable($file)) {$this->log[] = "無權限刪除: $file";continue;}if (unlink($file)) {$deleted++;} else {$this->log[] = "刪除失敗: $file";}}return $deleted;}public function getLog() {return $this->log;}}// 使用示例$deleter = new BatchDeleter();$count = $deleter->deleteFilesByPattern('/tmp/*.tmp');echo "已刪除 {$count} 個臨時文件";// 查看錯誤日誌if (!empty($deleter->getLog())) {echo "