search
HomePHP FrameworkThinkPHPSolve the cross-domain problem of session in thinkphp

Solve the cross-domain problem of session in thinkphp

When used locally, everything is normal; both the back-end project and the front-end project are deployed to the server, and everything is normal; after the back-end project is deployed to the server, and cross-domain access is set to allow cross-domain access, the local front-end project When using the back-end project interface on the server, a problem arises:

First, use postman to test the interface for obtaining the image verification code and verifying the image verification code interface, which is normal.

Then, use the interface to obtain the image verification code in html, it works fine; finally, use the interface to verify the image verification code in JS, but an error occurs! ! !

Analysis

Through the problem description, we can see that the problem occurs across domains. So, there are two possibilities, one is because the cross-domain settings are incorrect; the other is because of a problem with thinkphp itself.

Using another cross-domain configuration, the problem still exists. That is a problem with thinkphp itself. After searching for information, the problem is located in thinkphp's session cross-domain.

Cross-subdomain solution

In fact, whether it is ThinkPHP or PHP itself, session.cookie_domain needs to be set when solving session cross-domain problems.
The solutions to the problem of cross-domain session mainly include the following:

The first case: If there is no .htaccess file in the directory, that is, if the url is not pseudo-static, then, Add in the first line of conf/config.php:

ini_set('session.cookie_domain',".domain.com");//跨域访问Session

If you enable debugging, it can be used! But if debugging is turned off, it doesn't work!

Second case: If there is a .htaccess file in your directory, then you add in the root directory, the first line of index.php:

This method does not matter whether it is enabled or not. It works for debugging!

However, our problem is not a cross-subdomain problem, but a completely cross-domain problem, so the above method is invalid.

Complete cross-domain solution

Get image verification code request

View the request information to get the image verification code, Request Headers are:

Accept:image/webp,image/*,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Cookie:pma_lang=zh_CN; pma_collation_connection=utf8_unicode_ci; pma_iv-1=wnpO4gv0eQRW1AMHmGr2ww%3D%3D; pmaUser-1=weZPqS0%2BW7nzFUVHRdqcfA%3D%3D
Host:api.voidking.com
Referer:http://localhost/ajax/ajax.html
User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36

Response Headers are:

Access-Control-Allow-Origin:*
Cache-Control:post-check=0, pre-check=0
Cache-Control:private, max-age=0, no-store, no-cache, must-revalidate
Connection:keep-alive
Content-Type:image/png
Date:Sun, 27 Nov 2016 12:10:44 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Pragma:no-cache
Server:nginx
Set-Cookie:PHPSESSID=721t4sqanvsii550m1dk8gq1o3; path=/; domain=.voidking.com
Transfer-Encoding:chunked

Verification verification code request

View the request information for verification verification code, Request Headers are:

Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:9
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:api.voidking.com
Origin:http://localhost
Referer:http://localhost/ajax/ajax.html
User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36

Response Headers are:

Access-Control-Allow-Origin:*
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html; charset=UTF-8
Date:Sun, 27 Nov 2016 12:13:21 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Pragma:no-cache
Server:nginx
Set-Cookie:PHPSESSID=149t0hhs2icqaaemvp39onkgp4; path=/; domain=.voidking.com
Transfer-Encoding:chunked
Vary:Accept-Encoding

Get the image verification code request again

Request Headers are:

Accept:image/webp,image/*,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:max-age=0
Connection:keep-alive
Cookie:pma_lang=zh_CN; pma_collation_connection=utf8_unicode_ci; pma_iv-1=wnpO4gv0eQRW1AMHmGr2ww%3D%3D; pmaUser-1=weZPqS0%2BW7nzFUVHRdqcfA%3D%3D; PHPSESSID=721t4sqanvsii550m1dk8gq1o3
Host:api.voidking.com
Referer:http://localhost/ajax/ajax.html
User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36

Response Headers are:

Access-Control-Allow-Origin:*
Cache-Control:private, max-age=0, no-store, no-cache, must-revalidate
Cache-Control:post-check=0, pre-check=0
Connection:keep-alive
Content-Type:image/png
Date:Sun, 27 Nov 2016 13:26:21 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Pragma:no-cache
Server:nginx
Transfer-Encoding:chunked

Comparison of three requests

Solve the cross-domain problem of session in thinkphp

#The first time to obtain the image verification code request, there is no PHPSESSID in the cookie, so the return information contains Set-Cookie. In the second request to obtain the image verification code, the cookie contains PHPSESSID, so Set-Cookie is not included in the return information.

And the PHPSESSID in the information Set-Cookie returned by the first request is the same as the PHPSESSID in the request information Cookie in the second request.

The ajax request to verify the image verification code does not have a cookie, and naturally there is no PHPSESSID, so the return information also contains Set-Cookie.

It can be seen that we need to make some modifications on the front end to send the request with Cookie.

Front-end jquery settings

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>jquery</title>
</head>
<body>
    <p>
        <img src="/static/imghwm/default1.png"  data-src="http://api.voidking.com/owner-bd/index.php/Home/CheckCode/getPicCode"  class="lazy"   alt="">
        <input type="text" id="picCode">
        <input type="button" id="send" value="验证">
    </p>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
    $(function(){
        $(&#39;#send&#39;).click(function(){
            //console.log(document.cookie);
            $.ajax({
                url: &#39;http://api.voidking.com/owner-bd/index.php/Home/CheckCode/checkPicCode&#39;,
                type: &#39;POST&#39;,
                crossDomain: true,
                xhrFields: {
                    withCredentials: true
                },
                dataType: &#39;json&#39;,
                data: {code: $(&#39;#picCode&#39;).val()},
                success: function(data){
                    console.log(data);
                },
                error: function(xhr){
                    console.log(xhr);
                }
            });
        });
    });
</script>
</body>
</html>

The error when requesting is as follows:

A wildcard &#39;*&#39; cannot be used in the &#39;Access-Control-Allow-Origin&#39; header when the credentials flag is true. Origin &#39;http://localhost&#39; is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.

A cross-domain error occurred. It can be seen that the backend also needs to make some modifications so that It can receive cross-domain cookies.

Backend nginx settings

add_header Access-Control-Allow-Origin http://localhost;
add_header Access-Control-Allow-Credentials true;

Note:
When the server-side Access-Control-Allow-Credentials parameter is true, the Access-Control-Allow-Origin parameter The value cannot be *.

After the backend nginx is set up, jquery's ajax request is normal and cookies can be carried. The backend receives data normally and returns the data.

Since angular's ajax request is different from jquery, we also need to study how angular sends cross-domain requests carrying cookies.

Front-end angular settings

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>angular</title>
    <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="myApp" >
    <p ng-controller="myCtrl">
        <img src="/static/imghwm/default1.png"  data-src="http://api.voidking.com/owner-bd/index.php/Home/CheckCode/getPicCode"  class="lazy"   alt="">
        <input type="text" id="picCode" ng-model="picCode">
        <input type="button" ng-click="send()"  value="验证">
    </p>
<script>
    var app = angular.module(&#39;myApp&#39;, []);
    app.controller(&#39;myCtrl&#39;, function($scope, $http, $httpParamSerializer) {
        $scope.send = function(){
            $http({
                method:&#39;POST&#39;,
                url:&#39;http://api.voidking.com/owner-bd/index.php/Home/CheckCode/checkPicCode&#39;,
                headers:{
                    &#39;Content-Type&#39;:&#39;application/x-www-form-urlencoded&#39;
                },
                withCredentials: true,
                dataType: &#39;json&#39;,
                data: $httpParamSerializer({code: $scope.picCode})
            }).then(function successCallback(response) {
                console.log(response.data);
                $scope.username = response.data.username;
            }, function errorCallback(response) {
                console.log(response.data);
            });
        }
    });
</script>

</body>
</html>

Recommended tutorial: "TP5"

The above is the detailed content of Solve the cross-domain problem of session in thinkphp. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
thinkphp是不是国产框架thinkphp是不是国产框架Sep 26, 2022 pm 05:11 PM

thinkphp是国产框架。ThinkPHP是一个快速、兼容而且简单的轻量级国产PHP开发框架,是为了简化企业级应用开发和敏捷WEB应用开发而诞生的。ThinkPHP从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的同时,也注重易用性。

一起聊聊thinkphp6使用think-queue实现普通队列和延迟队列一起聊聊thinkphp6使用think-queue实现普通队列和延迟队列Apr 20, 2022 pm 01:07 PM

本篇文章给大家带来了关于thinkphp的相关知识,其中主要介绍了关于使用think-queue来实现普通队列和延迟队列的相关内容,think-queue是thinkphp官方提供的一个消息队列服务,下面一起来看一下,希望对大家有帮助。

thinkphp的mvc分别指什么thinkphp的mvc分别指什么Jun 21, 2022 am 11:11 AM

thinkphp基于的mvc分别是指:1、m是model的缩写,表示模型,用于数据处理;2、v是view的缩写,表示视图,由View类和模板文件组成;3、c是controller的缩写,表示控制器,用于逻辑处理。mvc设计模式是一种编程思想,是一种将应用程序的逻辑层和表现层进行分离的方法。

实例详解thinkphp6使用jwt认证实例详解thinkphp6使用jwt认证Jun 24, 2022 pm 12:57 PM

本篇文章给大家带来了关于thinkphp的相关知识,其中主要介绍了使用jwt认证的问题,下面一起来看一下,希望对大家有帮助。

thinkphp扩展插件有哪些thinkphp扩展插件有哪些Jun 13, 2022 pm 05:45 PM

thinkphp扩展有:1、think-migration,是一种数据库迁移工具;2、think-orm,是一种ORM类库扩展;3、think-oracle,是一种Oracle驱动扩展;4、think-mongo,一种MongoDb扩展;5、think-soar,一种SQL语句优化扩展;6、porter,一种数据库管理工具;7、tp-jwt-auth,一个jwt身份验证扩展包。

thinkphp 怎么查询库是否存在thinkphp 怎么查询库是否存在Dec 05, 2022 am 09:40 AM

thinkphp查询库是否存在的方法:1、打开相应的tp文件;2、通过“ $isTable=db()->query('SHOW TABLES LIKE '."'".$data['table_name']."'");if($isTable){...}else{...}”方式验证表是否存在即可。

一文教你ThinkPHP使用think-queue实现redis消息队列一文教你ThinkPHP使用think-queue实现redis消息队列Jun 28, 2022 pm 03:33 PM

本篇文章给大家带来了关于ThinkPHP的相关知识,其中主要整理了使用think-queue实现redis消息队列的相关问题,下面一起来看一下,希望对大家有帮助。

thinkphp3.2怎么关闭调试模式thinkphp3.2怎么关闭调试模式Apr 25, 2022 am 10:13 AM

在thinkphp3.2中,可以利用define关闭调试模式,该标签用于变量和常量的定义,将入口文件中定义调试模式设为FALSE即可,语法为“define('APP_DEBUG', false);”;开启调试模式将参数值设置为true即可。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft