Do Cookies Need to be Sanatized Before Being Saved?

This maybe just a personal distinction but I consider:

  • data validation to mean is the data ‘correct’? Is it what we expect?
  • data sanitisation to mean is the data *safe to use *

Though there can be some blurring, typically data validation will only occur when a user-input is taken, or some data is obtained and we wish to make sure its ‘correct’ before we use it. This might be if we expect an integer, is it an integer, if its we expect a date, is it of the correct form? The options API allows you to define a validation callback for your settings.

Data sanitisation is about making the data safe. And this should be done anytime you use the data. Best practise is to sanitise late, i.e. only sanitise just before you use it. Typically you don’t have to worry about this for saving to the databse if you’re using the api functions such as update_option(), update_post_meta() etc (but you do when handling the database directly).

But what is safe depends on context. Is the data intended to be used as an url, in a text input, in text-area, or an SQL query?

So it depends you how you intend to use the variable $full_site_cookie on how you should sanitise it.


In the above you use $get_cookie_check = wp_kses($_GET['view_full_site'],null);. wp_kses() is expensive and it seems you expect the $_GET['view_full_site'] to be ‘true’. Why not just be strict with it:

$get_cookie_check = ( !empty( $_GET['view_full_site'] ) )
                      && 'true' == strtolower( $_GET['view_full_site'] ) );
//$get_cooke_check is now a boolean.

Leave a Comment