1. 程式人生 > >ThinkPHP中的跨域名共享session

ThinkPHP中的跨域名共享session

大笑經過一段時間的研究,終於取得突破

兩個網站:

think.local

think2.local

主要原理是:

1、通過在think.local執行js指令碼,訪問think2.local的介面,將cookie的PHPSESSID傳遞過去

2、修改think2.local的cookie中的PHPSESSID與think.local一致,從而在think2.local中可以與think.local訪問同一個session

3、補充:在同一個伺服器中,而且兩個網站使用的session資料夾都是php預設

主要程式碼:

think.local部分:

//測試同步登入
    public function test(){
        session('uid',111);
        $session_id=session_id();
        //同步測試
        $gotourl='<script type="text/javascript" src="http://www.think2.local/api/SynLogin/index/token/thinkphp/session_id/'.$session_id.'"></script>';
        //echo htmlspecialchars($gotourl);exit;
        echo $gotourl;
        echo 'ok';exit;
    }
think2.local部分
//同步登入頁
    public function Index(){
        $token=I('get.token');
        if($token!='thinkphp'){
            echo 'wrong';exit;
        }else{
            //同步登入操作
            $session_id=I('get.session_id');
            //$session_id='mh23hdn3h34j2efpno1k95bhm6';
            cookie('PHPSESSID',$session_id);
        }
    }

在think2.local的任意操作中 dump(session());即可獲取與think.local一致的session值,從而實現共享session。

PS:可以做跨域名登入了,如果是不同伺服器,可以考慮將session資訊存入資料庫/Redis/Memcached等.