cookie snippets

How to set a cookie, remove a cookie and get the value of a cookie in PHP

Tagged php, cookie, management, set, remove, get  Languages php

PHP cookie management is a good example of how incredibly badly designed PHP is:

Set a cookie that expires when browser is closed

Note that you most probably want to set the path, which we do here:

$value = 0;
$expires = 0;
setcookie('cookie_name', $value, $expires, '/');

Remove cookie

setcookie ('cookie_name', FALSE, time()-10000);

Get cookie value

$_COOKIE['cookie_name']

Testing sessions with Sinatra and Rack::Test

Tagged session, test, sinatra, rack, cookie, rack::test, mocha  Languages ruby

You need support for testing sessions when, for example, testing authentication. The only way I've managed to get sessions to work with Sinatra and Rack::Test is by going through the whole stack, in other words calling the authentication controller as shown here:

@user = Factory(:user) # create a dummy user
User.expects(:authenticate).with(any_parameters).returns(@user) # make authenticate return the dummy user
post "/sign-in", {:email => @user.email, :password => @user.password} # login to the application and set a session variable.

After this the session populated and we're logged in when accessing the application again:

post "/articles", {:title => 'Sessions suck', :body => '...'}

On a side note, there are two ways of specifying sessions that used to work, but which no longer work with Sinatra 1.0:

get '/', :env => { :session => {:abc => 'adf'} }
get '/', {}, :session => {:abc => 'adf'}
get '/', {}, "rack.session" => {:abc => 'adf'}

The session is always empty.

There are many discussions about sessions and Rack::Test, but not one of them has a solution that works for me: * rack.session variable is missing env under test environment * Sessions with rspec and Rack.Test

How to store form data in a cookie with jQuery and the cookie plugin

Tagged jquery, cookie, form, data, persist  Languages javascript
/**
 * Makes form data persistent by storing the data in cookies.
 */
(function($){
  /**
   * Load value from cookie, and set cookie when value is changed.
   */
  $.fn.persist = function(namespace) {
    if(!namespace) {
      namespace = "";
    }
    return this.each(function() {
      var $this = $(this);
      var id = $this.attr('id');
      var cookie_name = namespace + id;
      var value;

      // Store changes in a cookie
      $this.change(function() {
        $.cookie(cookie_name, $this.val());
      });

      value = $.cookie(id);
      // Don't overwrite value if it's set
      if(!$this.val()) {
        $this.val(namespace + value);
      }
    });
  };
})(jQuery); 

$(document).ready(function(){
  $('.persistent').persist();
});

How to Implement Flash for Sinatra with Cookies

Tagged flash, sinatra, ruby, rails, cookie, rack-flash  Languages javascript, ruby, css

Storing your application’s flash messages in a cookie means you can cache the whole page.

Ruby/Sinatra

def flash(key, value)
  fail "Invalid key '#{key}'" unless [ :info, :error ].include?(key)
  response.set_cookie "flash_#{key}", value: I18n.t(value), path: '/'
end

Put the code in a helper or controller.

Javascript

var Flash;

Flash = (function() {
  function Flash(flash_holder, cookie_prefix) {
    this.flash_holder = flash_holder;
    this.cookie_prefix = cookie_prefix;
    if (this.flash_holder == null) {
      this.flash_holder = '#flash';
    }
    if (this.cookie_prefix == null) {
      this.cookie_prefix = 'flash_';
    }
  }

  Flash.prototype.show = function() {
    var i, key, len, name, ref, results, value;
    ref = ['info', 'error'];
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      key = ref[i];
      name = this.cookie_prefix + key;
      value = Cookies.get(name);
      if (value) {
        $(this.flash_holder).attr('class', name).html(value).show('fast');
        results.push(Cookies.remove(name));
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  return Flash;

})();

$(function() {
  new Flash().show();
  return new Flash('#flash_holder', 'cookie_prefix').show();
});

HTML

<div id="#flash"></div>

CSS

#flash {
  display: none
}

.flash_info {
  color: darkgreen
}

.flash_error {
  color: darkred
}

Usage

In your controller:

get '/' do
  flash :info, 'login.failed'
end

Dependencies