Track the Users' Data/Recent Searches: COOKIE vs SESSION Approach

Public

If you want to track the users' data/behaviors, you could use COOKIE or SESSION variables.

SESSION values last for the entire session duration with the server and ends when you log-out or close the browser/tab. COOKIE values are saved in a small file and persist across multiple sessions, even when you close the browser/tab. It's easy to set and get COOKIE/SESSION variables in Drupal, even for Anonymous Users. In any case, the COOKIE/SESSION variables are accessible across the site pages. See also: http://buildinternet.com/2010/07/when-to-use-_session-vs-_cookie/.

The sample code below shows the recently searched keyword for users. It assumes that the Search block is enabled in the currently active theme, and accessible for site users.

</> CopyGet raw version
php
  1. function mymodule_form_alter(&$form, &$form_values) {
  2. if ($form['#form_id'] == 'search_block_form') {
  3. // Attach a custom behavior upon submitting the search keyword in the search block.
  4. $form['#submit'][] = '_search_submit';
  5. }
  6. }
  7.  
  8. function _search_submit(&$form, &$form_values) {
  9. // Create a new COOKIE called $_COOKIE['Drupal_visitor_recent_search']
  10. // using the entered/submitted search keyword as the COOKIE value.
  11. user_cookie_save(array('recent_search' => $form_values['values']['search_block_form']));
  12.  
  13. // Uncomment the code block below for SESSION-based approach.
  14. // $_SESSION['recent_search'] = $form_values['values']['search_block_form'];
  15. }
  16.  
  17. function mymodule_init() {
  18. // Check if there's a previously searched keyword upon page loading.
  19. // COOKIE values in Drupal are stored as $_COOKIE['Drupal_visitor_<KEY>'].
  20. // It could be accessed in JavaScript also as Drupal.visitor.<KEY>.
  21. // When using Drupal Behaviors (and the misc/jquery.cookie.js is loaded),
  22. // you could access the cookie using $.cookie('Drupal.visitor.recent_search').
  23. if (isset($_COOKIE['Drupal_visitor_recent_search'])) {
  24. drupal_set_message('You recently searched for ' . $_COOKIE['Drupal_visitor_recent_search']);
  25. }
  26.  
  27. // Uncomment the code block below for SESSION-based approach.
  28. /* if (isset($_SESSION['recent_search'])) {
  29.   drupal_set_message('You recently searched for ' . $_SESSION['recent_search']);
  30.   } */
  31. }