简体   繁体   中英

Jquery cross domain login with PHP sessions

I have two websites

  • www.example.com
  • www.m.example.com

The all PHP scripts are based on the first domain. I need to login user from the mobile site using the first domain PHP scripts. And I need to make sessions over the domains. How can I do this?

PHP file:

<?php
session_start();

$username = $_POST['username'];
$password = md5($_POST['password']);

//DB check

$_SESSION['log'] = $dbarray;
?>

The script on the second domain

$.post('../scripts/login.php',{username:username,password:password},function(data){
  //Success
});

Are the two domain running on the same server and Apache+PHP stack? In that case, you just need to set the cookies for .example.com instead of www.example.com (the default). The session data is stored on the same server, so the session can be shared.

<?php
ini_set('session.cookie_domain', '.example.com');

session_start();
...

You can take a look at this answer Sharing php Session ($_SESSION) across multiple domain

For JS side, since cross-domain ajax is not allowed. I suggest using a <form> element, specify a redirect parameter, so that your login script (login.php) can redirect the user back to the right place after login. (you also need to add code in login.php to handle the redirect)

<form id="loginForm" action="http://www.example.com/script/login.php" method="post">
 <input type="hidden" name="username" value="..."/>
 <input type="hidden" name="password" value="..."/>
 <input type="hidden" name="redirect" value="http://www.m.example.com/" />
</form>

<script>$("#loginForm").submit();</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM