How can JSON encoding and decoding be used to prevent security vulnerabilities when working with cookies in PHP?

When working with cookies in PHP, using JSON encoding and decoding can prevent security vulnerabilities by ensuring that the data stored in cookies is properly formatted and sanitized. By encoding data as JSON before storing it in a cookie, you can prevent malicious users from injecting harmful code into the cookie data. When decoding the cookie data, make sure to use JSON decoding to safely retrieve the data without risking security vulnerabilities.

// Encode data as JSON before storing in a cookie
$data = array("username" => "john_doe", "role" => "admin");
$encoded_data = json_encode($data);
setcookie("user_data", $encoded_data, time() + 3600, "/");

// Decode JSON data from cookie
if(isset($_COOKIE['user_data'])){
    $decoded_data = json_decode($_COOKIE['user_data'], true);
    echo "Username: " . $decoded_data['username'] . "<br>";
    echo "Role: " . $decoded_data['role'];
}