How can the PHP code snippet be improved to prevent the "Sesion has expired" error and ensure proper session handling?

The issue of "Session has expired" error can be prevented by setting the session timeout properly and handling session regeneration. To ensure proper session handling, we can regenerate the session ID periodically to prevent session fixation attacks and ensure that the session does not expire unexpectedly.

// Set session timeout to 30 minutes
session_start();
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    session_unset();
    session_destroy();
}
$_SESSION['LAST_ACTIVITY'] = time();

// Regenerate session ID every 30 minutes
if (!isset($_SESSION['CREATED'])) {
    $_SESSION['CREATED'] = time();
} elseif (time() - $_SESSION['CREATED'] > 1800) {
    session_regenerate_id(true);
    $_SESSION['CREATED'] = time();
}