简体   繁体   中英

How to secure cookies in php?

How does session_set_cookie_params work? I want to ensure all cookies are set with httponly=true , and secure=true . But instead of adding these arguments to every call to setcookie(), I can just - before session_start() - set them in session_set_cookie_params() ? And henceforth, every call to setcookie sets those params i each and every cookie? That would save a lot of tedious work (and surely error-prone). I would imagine something like this

$cookieParams = session_get_cookie_params();
$cookieParams['httponly'] = true;
$cookieParams['secure'] = true;
session_set_cookie_params($cookieParams);
session_start();

So now, if I do:

 setcookie("ABC_user", "", time()+3600);

That cookie has those params in argument 6 and 7 set? Is there a way to check that it works? Or is there an even better way to accomplish this?

This simple code will give you what you want.

function set_cookie($name,$content,$time){
$http_only = true;
$secure = true;
$path = "/";
$domain = ".example.com"; // Include All Subdomains
setcookie($name,$content,$time,$path,$domain,$secure,$http_only);
}

set_cookie("ABC_user", "", time() + 3600);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM