How can PHP scripts be used to automatically delete users who have not logged in for more than 2 months?

To automatically delete users who have not logged in for more than 2 months, we can create a PHP script that checks the last login date of each user and deletes those who have not logged in for more than 2 months. This can be achieved by querying the database for users who meet the criteria and then deleting them from the database.

<?php
// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Define the cutoff date (2 months ago)
$cutoffDate = date('Y-m-d', strtotime('-2 months'));

// Query to select users who have not logged in for more than 2 months
$query = "SELECT * FROM users WHERE last_login < '$cutoffDate'";

$result = mysqli_query($connection, $query);

// Loop through the results and delete the users
while ($row = mysqli_fetch_assoc($result)) {
    $userId = $row['id'];
    $deleteQuery = "DELETE FROM users WHERE id = $userId";
    mysqli_query($connection, $deleteQuery);
}

// Close the connection
mysqli_close($connection);
?>