What are best practices for automatically deleting inactive user accounts in PHP after a certain period of time?
Automatically deleting inactive user accounts in PHP after a certain period of time helps maintain database cleanliness and security by removing unused accounts. One way to achieve this is by setting a timestamp for the last login or activity of each user and then periodically checking and deleting accounts that have been inactive for a specified duration.
// Check for inactive user accounts and delete them
$inactive_duration = 90; // 90 days of inactivity before deletion
$current_time = time();
// Query to select inactive users
$query = "SELECT id FROM users WHERE last_login < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL $inactive_duration DAY))";
$result = mysqli_query($connection, $query);
// Delete inactive users
while ($row = mysqli_fetch_assoc($result)) {
$user_id = $row['id'];
$delete_query = "DELETE FROM users WHERE id = $user_id";
mysqli_query($connection, $delete_query);
}
Related Questions
- How can cronjobs be utilized in PHP to achieve specific tasks like writing values to a text file at regular intervals?
- What are the potential implications of setting file permissions to 777 in a PHP application, as mentioned in the tutorial?
- What is the significance of using number_format in PHP for displaying numbers in a specific format?