在php中安全会话/ cookie

2 php cookies session

我对会话有疑问.你如何建立一个安全的登录会话/ cookie.我在看这个例子,他们将这个数组添加到会话中:

$data = array{

    username = $_POST['username'];
    is_logged = true;

}
Run Code Online (Sandbox Code Playgroud)

我想知道这是否足够?是不是可以将cookie中的用户名更改为任何内容或任何人?有什么好办法可以解决这个问题?

或者这是完全安全的,我错过了什么?

另外,你们怎么看待在数据库中存储会话?我知道CI有一个内置功能来做到这一点.这会导致任何性能方面的问题,还是值得鼓励?

djn*_*djn 11

I believe you are misunderstanding how a PHP session is supposed to work. You can safely store the username, login status and other stuff into the $_SESSION array, as this is stored serverside. The only thing sent to the browser is a single cookie (named PHPSESSID unless you changed this in php.ini) containihg the session ID - which is a unique random number.

Once your visitor has an active session every time he requests a page which has session_start() at the top, session_start() will look at the request for a cookie named PHPSESSID, read the serverside session file (if the session exists and is valid) and restore the filed $_SESSION array. This array never needs to leave the server.

The session cookie is set without an expiration date (unless you mess with the session.cookie_lifetime option in php.ini), so the browser deletes it at shutdown. The session file on the server has an expiration time itself, managed by session.gc_maxlifetime (in seconds).

Path to safer sessions:

  • make sure only cookies are used to pass the session id to the browser setting session.use_cookies=1, session.use_only_cookies = 1, session.use_trans_id = 0 (I'll spare you the details of the alternate syntax)
  • prevent session hijacking (i.e. somebody else faking an existing session) storing into $_SESSION something that identifies the browser - a common pattern is to store the md5() of the browser's User-Agent header, the Accept header, the remote IP address or a combination of those; check if it matches at every new request with an existing session id
  • if you're on a shared server you should indeed keep your session files separate from those of your server neighbours: set session.save_path to a folder only you and PHP have access to.

Finally, you should create a script to log users out of the session (and encourage them to use it instead of simply navigating away). This is a sample script:

<?php
  session_start();
  $params = session_get_cookie_params();
  setcookie(session_name(), '', 1, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));
  session_regenerate_id(true);
  session_destroy();
  session_write_close();
  header('Location: your_login_page.php');
  exit;
Run Code Online (Sandbox Code Playgroud)