Do Cookies Need to be Sanatized Before Being Saved?

I recently wrote a plugin and now I’m backtracking a bit to sanitize any and all user input. I know that I should sanitize anything that comes from $_GET or $_POST as a user can insert malicious scripts into that.

I also am sanitizing anything I’m calling via get_options that the user inputted just to be safe (not sure if the options.php API sanitizes but that’s another question).

But what about cookies? Do these need to be sanitized? If so how? Here is my function:

$get_cookie_check = wp_kses($_GET['view_full_site'],null); //sanitize user input
$site_url  =  site_url(); 
$domain  =  parse_url($site_url, PHP_URL_HOST);
    if($get_cookie_check =='true'){
        //set the cookie
        setcookie("nifty_cookie", 1, time()+86400, "https://wordpress.stackexchange.com/", $domain);
        $_COOKIE['nifty_cookie'] = 1;
    }
}
//cookie variable
$full_site_cookie= $_COOKIE['nifty_cookie']; 

I’m not thinking I need to sanitize anything here because I’m the one setting the cookie value (in this case to 1) via PHP. Is this a correct thought?

1 Answer
1

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