[Get/save/delete] cookie information

20

What are cookies?

Cookie is a mechanism to temporarily store information of users who visit the homepage. By storing various contents such as the date and time of the visit to the site, the number of visits, etc. as user information, it is possible to identify the user when the site is visited again and to save the trouble of entering the information.

(1) If you enter your ID and password and log in to the site once you have logged in, you can enter it without entering your ID and password if you access it again after a while. (2) When you visit a shopping site, you are already logged in, or the items you put in the cart remain as they are.

Both thanks to the login/cart information stored in cookies!! In this way, cookies play a role in making it convenient to access the website and making it possible to provide various services. (A lot of Internet banking is also unavailable without cookies enabled.)

Get a value from a cookie

Cookie retrieval is a basic and simple method. Just if multiple values are written to the cookie ";" Since it is obtained as a string separated by , it is amazing ~ very difficult to understand ...

var str = document.cookie;
// 「 key1=val1; key2=val2; key3=val3; ・・・ 」

Get cookies by key

Get the value from the cookie and set it to an associative array. This makes cookies much easier to work with.

// 連想配列に格納
function getCookieArray(){
    var arr = new Array();
    if(document.cookie != ''){
        var tmp = document.cookie.split('; ');
        for(var i=0;i<tmp.length;i++){
            var data = tmp[i].split('=');
            arr[data[0]] = decodeURIComponent(data[1]);
        }
    }
    return arr;
}

// keyを指定して取得
// 「 key1=val1; key2=val2; key3=val3; ・・・ 」というCookie情報が保存されているとする
var arr = getCookieArray();
var value = 'key1の値:' + arr['key1'];
// key1の値:val1

Storing and Deleting Cookies

Preparing for cookies

var kigen = 30; //Cookieの期限(1ヶ月とする)←適宜、適切な期限を設定
var nowdate = new Date(); //現在の日付データを取得
nowdate.setTime(nowdate.getTime() + kigen*24*60*60*1000); //1ヶ月後の日付データを作成
var kigendate = nowdate.toGMTString(); //GMT形式に変換して変数kigendateに格納
var cookievalue = "session_id=user_0001; ";
var expires = "expires=" + kigendate + "; ";
var path = "path=/";
var dt = new Date('1999-12-31T23:59:59Z'); // 過去の日付をGMT形式に変換

The value of the cookie (which is equivalent to the cookievalue in the source above) must not contain semicolons ( ; ), commas ( , ) or spaces, so encode the values you write with encodeURIComponent().

* From the viewpoint of security, it is not good to keep user information semi-permanently, so it is customary to set a deadline.

Write (save) data to a cookie

document.cookie = cookievalue + expires + path;

Delete cookie data

You can set an expiration date for "cookies", and when the expiration date has passed, the data of "cookies" is automatically deleted, so it is possible to delete them intentionally.

document.cookie = "session_id=; expires=" + dt.toUTCString() + "; "+ path
// 「expires=dt.toUTCString();」の部分は「max-age=0;」でもOK

"expires=dt.toUTCString()" means that the expiration date represents "past date" and "max-age = 0" means that the expiration date is "0 seconds" Whichever method you use, you can delete the cookie immediately.

Optional attributes of cookies

attribute substance
path The specified path is the scope of the cookie
expires Expiration date up to the specified date
max-age Expiration time for the specified number of seconds
domain The specified domain is the scope of the cookie
secure Cookies are only valid for https communication

I've never used Domain and Secure personally...

Dangers of Cookies [Session Hijacking]

Session hijacking by leaking cookie identifiers.

Cookies may contain login information together with the session ID of the site, and even if this information itself is encrypted with SSL etc., if you know the session ID, the login state will be reproduced by sending it to the server.

While cookies are convenient, you should also be aware that there are security risks, and if you want to increase security and protect your privacy, take measures such as changing your settings to delete cookies.

Share:
20
Author by

すとぷりさとみくん推しのITプログラマー꒰ ♥︎ ꒱ 日々の備忘録です( ˊᵕˋ )♡.°⑅

Updated on June 29, 2019