Is it necessary to store data both in sessions and cookies in PHP to prevent data loss?

To prevent data loss in PHP, it is not necessary to store data in both sessions and cookies. Sessions are typically more secure for storing sensitive data as they are stored on the server side, while cookies are stored on the client side and can be manipulated by users. It is recommended to store critical data in sessions and use cookies for non-sensitive information or for enhancing user experience.

// Start a session
session_start();

// Store data in session
$_SESSION['username'] = 'JohnDoe';

// Set a cookie with non-sensitive data
setcookie('theme', 'dark', time() + (86400 * 30), '/'); // Cookie expires in 30 days