How can PHP developers prevent unauthorized access to user data when using cookies for persistent login sessions?

To prevent unauthorized access to user data when using cookies for persistent login sessions, PHP developers should encrypt the sensitive user data stored in the cookie. This encryption ensures that even if a malicious user intercepts the cookie, they will not be able to decipher the data without the encryption key.

// Encrypt the user data before storing it in the cookie
function encryptData($data, $key) {
    return openssl_encrypt($data, 'AES-256-CBC', $key, 0, substr($key, 0, 16));
}

// Decrypt the user data when retrieving it from the cookie
function decryptData($data, $key) {
    return openssl_decrypt($data, 'AES-256-CBC', $key, 0, substr($key, 0, 16));
}

// Example of setting a cookie with encrypted user data
$userData = ['id' => 123, 'username' => 'john_doe'];
$encryptedData = encryptData(json_encode($userData), 'secret_key');
setcookie('user_data', $encryptedData, time() + (86400 * 30), '/');

// Example of retrieving and decrypting user data from the cookie
if(isset($_COOKIE['user_data'])) {
    $decryptedData = decryptData($_COOKIE['user_data'], 'secret_key');
    $userData = json_decode($decryptedData, true);
    // Use the decrypted user data as needed
}