在客户端防止操作cookie

I know that cookie only work with string and does not accept array... so far so good

Creating and reading a cookie:

setcookie( 'name' , 'my name is foo' );
echo $_COOKIE['name']; // output my name is foo 


If the user change the cookie name to: name[]
he changes the cookie name in an array and we get an error: Array to string conversion.

1) how can we prevent this kind of safe handling of cookies?
2) if we work with a class of cookie, the get method should return only strings?

You have two choices:

  1. Use session variables instead of cookies.

  2. Validate your cookes when you use them. One part of this could be encrypting the cookie value, and prepending a private key before the value. The script can decrypt the cookie and test whether it begins with the private key. You can also test whether the user renamed the cookie to an array:

    if (is_string($_COOKIE['name'])) {
        ...
    }