I want to store the zip code of a user, if they use it for a proximity search in a cookie. However, I don't know where or how to start to implement this.
How do I store anonymous user information on a cookie?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communitySince Drupal 7, there are two functions to store data in a cookie: user_cookie_save(), and user_cookie_delete(). Despite the function names, the functions work also for anonymous users, since they don't get information from the $user
object or any information that is related to the user ID.
comment_form_submit() uses user_cookie_save()
in the following code lines:
if (user_is_anonymous()) {
user_cookie_save(array_intersect_key($form_state['values'], array_flip(array('name', 'mail', 'homepage'))));
}
If you are using a version of Drupal that doesn't define that functions, you can implement similar functions in a module you use.
function mymodule_cookie_save(array $values) {
foreach ($values as $field => $value) {
// Set cookie for 365 days.
setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/');
}
}
function mymodule_cookie_delete($cookie_name) {
setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/');
}
Keep in mind that setrawcookie() is only available in PHP 5. If you are developing a module that could be used with PHP 4, then you should use setcookie(), and the code of the functions should be accordingly changed: the parameter needs to be declared as $values
(not array $values
), and the call to rawurlencode() needs to be removed as the cookies are already URL encoded from setcookie()
.
mymodule_cookie_save()
with user_cookie_save()
. You could also use user_cookie_save()
and user_cookie_delete()
for your functions, if you first check those functions are not already defined, which would happen if another module defines them for Drupal 6.
Setting cookies in Drupal is not different from how you would do it with any other PHP site:
setcookie
is the function that PHP provides for this. There is also the $_COOKIE
super global variable to use.
Code example:
$cookieval = 'my cookie value';
if ($_COOKIE['my_cookie_key'] != $cookie_val) {
setcookie('my_cookie_key', $cookie_val);
}
If you have Drupal installed in subfolder so that your site root URL has the form www.mydomain.com/mysite, you should probably use base_path() instead of '/' when setting the cookie.
Functions in kiamlaluno's answer would then be:
function mymodule_cookie_save(array $values) {
foreach ($values as $field => $value) {
// Set cookie for 365 days.
setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, base_path());
}
}
function mymodule_cookie_delete($cookie_name) {
setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, base_path());
}