开发者

PHP Sessions vs DB Sessions

开发者 https://www.devze.com 2023-03-29 21:21 出处:网络
I dabble in PHP. In the projects I\'ve done I always use the database and a cookie to handle sessions. I\'ve seen \"session functions\" such as session_start() being used also in o开发者_如何转开发the

I dabble in PHP. In the projects I've done I always use the database and a cookie to handle sessions. I've seen "session functions" such as session_start() being used also in o开发者_如何转开发ther sources. I'm just curious, which is better? Should I be using one or another?


Well, there's three ways that I've used through-out time:

  1. The traditional $_COOKIE-way, meaning that you actually use cookies to store values
  2. The "new" $_SESSION-way, where you use an associative array that probably relies on a cookie
  3. Using $_SESSION in conjunction with the DB, making sessions controllable on a user-basis.

I prefer using option #3, as it both enables me to alter sessions "on-the-fly", as well as track the logged in users easier.

Options #3 would play out in the following way (semi-pseudo):

<?php
    //Start the session
    session_start();

    //Get the session data
    $_SESSION['user'] = retrieveSessionDataFromDB($_SESSION['user']['unique_id']);

    //Profit
?>


I would recommend using the built in session functions because you don't have to code all the session handling manually. By default the session state is stored in a file, but you can also change it e.g. to the database using session_set_save_handler.


I would absolutely use PHP Sessions, for a couple of reasons

  1. First reason is that PHP Sessions are easily managed with native methods. There are also plenty of libraries that allow very robust Session management, such as Zend_Session

  2. PHP Sessions are more scalable. Using MySQL as your data storage will likely be your biggest bottleneck once your application starts to grow. Storing sessions in memory will allow you to scale horizontally to compensate. Storing in the database could put more strain on your database than it needs.

Typically, though, it doesn't matter much for small applications, but if you plan to grow I would definitely use PHP Sessions.

0

精彩评论

暂无评论...
验证码 换一张
取 消