I'm using a slightly modified version of the login scrips found here, and have run into behavior I think is coming from session_set_cookie_params() that I do not understand.
I am using sessions, cookies, and header() to redirect users to a login page, then back to the page they requested. My problem was that, even though the initial page and the login page use the same function to handle sessions and cookies, two separate cookies were being set; one for www.example.com and one for example.com. This was preventing a session variable set on the initial page from being read after login.
Here is an example of code from any requested page:
requireSSL();
sec_session_start();
if(login_check($mysqli) == false) {
$_SESSION['origURL'] = $_SERVER['REQUEST_URI'];
header('Location: https://www.example.com/login.php');
exit();
}
Here are the functions:
function requireSSL() {
if($_SERVER["HTTPS"] != "on") {
header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
exit();
}
}
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = true; // Set to true if using https.
$httponly = true; // This stops javascript being able to access the session id.
ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies.
$cookieParams = session_get_cookie_params(); // Gets current cookies params.
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
session_name($session_name); // Sets the session name to the one set above.
session_start(); // Start the php session
session_regenerate_id(true); // regenerated the session, delete the old one.
}
Although I was able to "fix" this behavior by explicitly stating a domain in session_set_cookie_params() (e.g. "example.com"), I would love to understand why two cookies were being set in the first place. Thanks!