1. <?php
  2. /**
  3. * Cleans up user data artifacts for debugging purposes.
  4. * Implements fallback logic for database connection issues.
  5. *
  6. * @param string $user_id The ID of the user whose data to clean up.
  7. * @param array $allowed_tables An array of table names to allow cleanup (default: ['user', 'sessions']).
  8. * @return bool True on success, false on failure.
  9. */
  10. function cleanupUserArtifacts(string $user_id, array $allowed_tables = ['user', 'sessions']): bool
  11. {
  12. $db_host = 'localhost'; // Default database host
  13. $db_name = 'your_database_name'; // Replace with your database name
  14. $db_user = 'your_database_user'; // Replace with your database user
  15. $db_pass = 'your_database_password'; // Replace with your database password
  16. // Attempt to connect to the database
  17. try {
  18. $conn = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
  19. $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  20. } catch (PDOException $e) {
  21. // Fallback: Log the error and attempt cleanup without database access.
  22. error_log("Database connection failed: " . $e->getMessage());
  23. echo "Database connection failed. Attempting cleanup without database access.\n";
  24. //Implement cleanup logic here without database connection if needed.
  25. return false; // Indicate failure
  26. }
  27. $tables = $allowed_tables;
  28. foreach ($tables as $table) {
  29. $sql = "DELETE FROM `$table` WHERE `user_id` = :user_id";
  30. try {
  31. $stmt = $conn->prepare($sql);
  32. $stmt->bindParam(':user_id', $user_id, PDO::PARAM_STR);
  33. $stmt->execute();
  34. echo "Cleaned up data for user ID: $user_id in table: $table\n";
  35. } catch (PDOException $e) {
  36. error_log("Error cleaning up data for user ID $user_id in table $table: " . $e->getMessage());
  37. // Log the error but continue to the next table.
  38. }
  39. }
  40. $conn = null; // Close the database connection.
  41. return true;
  42. }
  43. // Example usage:
  44. //$user_id_to_clean = '123';
  45. //if (cleanupUserArtifacts($user_id_to_clean)) {
  46. // echo "User data cleanup successful.\n";
  47. //} else {
  48. // echo "User data cleanup failed.\n";
  49. //}
  50. ?>

Add your comment