codesuck codesuck - 1 month ago 10
PHP Question

Session is not starting in my sub domain php

I have tried every method to start a session in sub domain but is not working

Here is sample of my php login code

<?php
if(isset($_POST['login'])){
$username = $_POST['login'];

//Database Query
if($everythingIsOkay){
session_set_cookie_params(0, "/", ".example.com", false, false);
session_start();
$_SESSION['username'] = $username;
$_SESSION['ini'] = true;
session_id();
header('Location:accountt.php');
}
}?>


Then I use this on top of every page in main domain

session_start();


This on sub.example.com i put this at the top of every file

<?php
session_set_cookie_params(0, "/", ".example.com", false, false);
session_start();
?>


But still is not working can someone tell me what to do?

Lastly i make this function and session is working in sub-domain but out in main domain

I added below function at the top of login script

<?php
function new_session_start(){
session_name();
$secure = false;
// This stops JavaScript being able to access the session id.
$httponly = false;
// Gets current cookies params. //$cookieParams["domain"],$cookieParams["lifetime"]
$cookieParams = session_get_cookie_params();
session_set_cookie_params(0,
$cookieParams["path"],
'.example.com',
$secure,
$httponly);
session_start(); // Start the PHP session
session_regenerate_id(true); // regenerated the session, delete the old one.
}
new_session_start();
?>


Then use this at the top of subdomain page

<?php
session_set_cookie_params(0, "/", ".example.com", false, false);
session_start();
session_regenerate_id(true);
?>

Answer

The problem here is not exactly the same as other poeple are thinking. On other questions they are talking about how to create a session for subdomain. It looks like you did everything correct as told on other questions. The problem here is in the session_set_cookie_params(0, "/", ".example.com", false, false).

You didn't add this code to your main page so the php will make that cookie by himself based on your domain. Your domain is example.com so your php will do it like session_set_cookie_params(0, "/", "example.com", false, false).

Then when you go to your subdomain he is searching for .example.com but he won't find it because the cookie of your main domain is example.com and not .example.com.

How to fix it: Add: session_set_cookie_params(0, "/", ".example.com", false, false); to your main page to so he will create the right cookie.