cookies vs sessions for php application

后端 未结 4 2001
猫巷女王i
猫巷女王i 2021-01-15 11:08

what would be better when implementing a php login system sessions or cookies ?

4条回答
  •  执念已碎
    2021-01-15 11:45

    Browser cookies:

    • shared between client (browser) and server (PHP)
      • amongst other things, that means "user can directly read/write the data, and you can't control or limit this"
    • limited in size (4K)
    • sent in full on every page request

    PHP sessions:

    • stored on server only
    • can be much larger than cookies
    • access through small cookie or request parameter

    PHP sessions are, in the background, creating a cookie (named PHPSESSID by default, configurable by session_name() ), so you're using cookies either way. The sessions can be configured not to use cookies, however this is a rather complicated workaround from times when cookie support was actually an issue. What it does: rewrites all the URLs it can find in the output, appending ?PHPSESSID=your_session_id to them. Problems: it used to miss some URLs, and the URL looks ugly (IMHO). I haven't seen a non-cookie PHP session in a long time (since 2002 or so).

    PHP sessions aren't the same as cookies, however in default config, they are using the cookie to store an "index"/"pointer" to your session data. Session data is stored on PHP server, when you have an existing session ID, the script gets access to corresponding data; whereas with pure cookies, you'd have to save the data into the cookie itself. Cookies are limited by size, and are sent on every page request, so it makes sense to only send a few bytes long cookie and store the data on server.

    Example:

    $_COOKIE: {
        'PHPSESSID' => 'a123456ebdf123'
    }
    
    $_SESSION: {
         'user_name' => 'Piskvor',
         8 => 'sadfsadfsdf',
         'huge block of text' => '(a huge block of text could be here, 
              as PHP sessions can usually be bigger than the measly 4K 
              allowed for a cookie)'
    }
    
    
    /tmp/php_sessions/sess_a123456ebdf123 (a file on server, note the name):
    (whatever you see in $_SESSION above, passed through serialize())
    

    This also means that you should never ever store into the cookie data that you don't want the user to see or modify - e.g. if your code sets a cookie logged-in-user: Piskvor, or even is-admin: 1, there's no way you can prevent the user from doing the same with built-in browser tools. Storing this in a session variable is more secure, as the data is not directly exposed to the user, except as your code allows - all the user sees is the session ID (session IDs aren't perfect, either - see "session hijacking" - but they are more secure than cookies).

    Edit for the TL;DR crowd: When using sessions, they are usually backed by cookies, but they are not the same thing. I would recommend using sessions (for reasons outlined above; be aware this usually means "through cookies").

提交回复
热议问题