1

I'm creating a site that as a subdomain www.login.example.com of the main site www.example.com. When the user logs in (from the subdomain) the username and password are passed to the main site by this ajax script:

 <script>

    var xmlhttp;

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }

    else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    function loginano() {

        var div= document.getElementById('thes').value;
        var username = document.getElementById('username').value;
        var password = document.getElementById('password').value;

        xmlhttp.open('POST', "https://example.com/sess.php", true);

        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

        xmlhttp.send('username='+username+'&password='+password);

        xmlhttp.onreadystatechange=function() {

            if (xmlhttp.readyState==4 && xmlhttp.status==200) {

                var resp = JSON.parse(xmlhttp.responseText);

                if(resp.status) {
                    div.innerHTML = "Great"; 
                }else {
                    div.innerHTML = "Nope";    
                }
            }else{ 
                    div.innerHTML = "Wait";
            }
        }
    }

</script> 

The post data are received and processed by this PHP code:

<?php
header("Access-Control-Allow-Origin: *");
session_start();
$servername = "localhost";
$username = "username";
$password = "pass";
$dbname = "dbname";

$loginusername = $_POST["username"];
$loginpassword = md5($_POST["password"]);

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql="SELECT * FROM tbl_users WHERE username='$loginusername' ";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
	
    while($row = $result->fetch_assoc()) {
                            $sessionid = $row['id'];
                            $sessionuser = $row['username'];
		$userpassword = $row['password'];
	
}}
	if($loginpassword == $userpassword){
 $_SESSION ["sessionid"]= $sessionid;
 $_SESSION ["sessionuser"]= $sessionuser;
$return_arr["status"]=1;
} else {
	$return_arr["status"]=0;	
}
echo json_encode($return_arr); // return value 
exit();
$conn->close();
?>

The login works and it is successful but the session does not start. What am I missing or what could be the problem?

3
  • How do you know the session doesn't get started? Any errors? Where do you try getting $_SESSION afterwards? Commented Jun 19, 2016 at 10:13
  • It does not start the session because I have wrote a script to check the session, here; Commented Jun 19, 2016 at 11:11
  • code<?php session_start(); if(isset($_SESSION["sessionid"])){ echo $_SESSION ["sessionid"]."kk"; }else{ echo "nope"; } ?>code Commented Jun 19, 2016 at 11:12

1 Answer 1

1

Session ids are passed around using cookies by default. Since your websites are on different domains (a subdomain is a different domain) the session cookie does not transfer over, so that's one thing that prevents cross-domain sessions from working.

Even if the cookie were not a problem, you would need to have the session data on some storage commonly accessible by your domains. You can use the file system or a db in order to share session data.

Another way might be to append the session Ids to the query string of all your requests (PHP even has some degree of built-in support for this). However, this way of doing things has many drawbacks -- the most important being that people copy/paste URLs all the time, with all that implies about revealing valid and reusing invalid session ids -- and therefore is strongly not recommended.

A much better approach would be to use Javascript to make cross-domain requests across all of the interested domains (maybe implementing a mediator design pattern). This way you can seamlessly transfer your session id across as many servers as you need to.

Edit: Remember that to use cookie-based sessions, session_start() must be called before sending anything to the browser so also before header("Access-Control-Allow-Origin: *");

Sign up to request clarification or add additional context in comments.

7 Comments

but the session is not passed to the subdomain. The subdomain page gets the username and password from the user then it passes them to www.example.com where it processes the data and create the session.
The session is used just within the website [www.example.com] and not shared to any other subdomain
What's the value of $sessionid out of the while, at line $_SESSION ["sessionid"]= $sessionid; ?
The value is the user ID on the database
I was asking because if id is specified, it will replace the current session id. session_id() needs to be called before session_start(). Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 , (comma) and - (minus)!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.