SoFunction
Updated on 2025-04-07

Detailed explanation of php's method to solve cross-domain problems

Strictly speaking, cross-domain means that as long as there is any difference between the protocol, domain name, and port, it is regarded as cross-domain.

For example, in actual projects, since the front and back ends separate the front and back ends, the current end needs to initiate a request to the backend through the interface, and cross-domain problems will occur. So, how to solve this kind of problem?

In fact, it is very simple to solve cross-domain problems. Just add the following code:

header("Access-Control-Allow-Origin:*");

Adding this line of code means that all domain names are allowed, but for security reasons, in actual projects, only a few fixed domain names and methods are allowed to be requested.

1. Allow access to a single domain name

header('Access-Control-Allow-Origin:');
header('Access-Control-Allow-Methods:POST');    // means that only POST requests are allowedheader('Access-Control-Allow-Headers:x-requested-with, content-type'); //Restrictions on request headers

2. No restriction on domain names

header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST');// means that only POST requests are allowedheader('Access-Control-Allow-Headers:x-requested-with, content-type');

3. Allow multiple domain names to access

In actual projects, it is best to specify a domain name that can be accessed across domains to increase security. It can be written in a public class and encapsulate a method call.

// Set the accessible domain namestatic public $originarr = [
   '',
   '',
];
 
/**
  * Public method call
  */
static public function setheader()
{
   // Get the current cross-domain domain name   $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
   if (in_array($origin, self::$originarr)) {
      // Allow cross-domain access of domain names in the $originarr array      header('Access-Control-Allow-Origin:' . $origin);
      // Response type      header('Access-Control-Allow-Methods:POST,GET');
      // Cross-domain access with cookies      header('Access-Control-Allow-Credentials: true');
      // Response header settings      header('Access-Control-Allow-Headers:x-requested-with,Content-Type,X-CSRF-Token');
   }
}

How to implement it on php

<?php
 
// Make arrangements to allow access to other domain namesheader("Access-Control-Allow-Origin:*");
 
// Response typeheader('Access-Control-Allow-Methods:POST');
 
// Response header settingsheader('Access-Control-Allow-Headers:x-requested-with, content-type');
 
//$callback = isset($_REQUEST['callback']) ? trim($_REQUEST['callback']) : ''; //jsonp callback parameter, required 
function getKey($key,$default=""){
    return trim(isset($_REQUEST[$key])?$_REQUEST[$key]:$default);
 
}
 
$id = getKey("id");
$conn = mysqli_connect("localhost","root","","test") or die("Connection failed");
$conn->query("set names utf8");
$sql = "select * from data where ".$id." is not null";
 
$result = $conn->query($sql);
 
$arr = [];
while($row=$result->fetch_assoc()){
    array_push($arr,json_encode($row));
 
}
 
$json = json_encode($arr);  //json dataprint_r($json);

4 Nginx reverse proxy

Using nginx reverse proxy to implement cross-domain is the easiest way to cross-domain. You only need to modify nginx's configuration to solve cross-domain problems, support all browsers, support session, no need to modify any code, and will not affect server performance.

Implementation idea: Configure a proxy server through nginx (domain name is the same as domain 1 and has different ports) as a springboard machine, reverse proxy accesses the domain2 interface, and can modify the domain information in the cookie by the way, so as to facilitate the writing of the current domain cookie and realize cross-domain login.

Modify the configuration file as follows:

// proxy serverserver {
    listen       81;
    server_name  ;
    location / {
        proxy_pass   http://:8080;  #Reverse Proxy        proxy_cookie_domain  ; #Modify the domain name in the cookie        index   ;
 
        # When accessing nignx using webpack-dev-server and other middleware proxy interfaces, there is no browser participation at this time, so there is no homologous restriction. The following cross-domain configurations cannot be enabled.        add_header Access-Control-Allow-Origin http://;  # When the current end only cross-domain without cookies, it can be *        add_header Access-Control-Allow-Credentials true;
    }
}

After the configuration is modified, restart nginx.

File access proxy server

// 
var xhr = new XMLHttpRequest();
// Front-end switch: Does the browser read and write cookies = true;
// Access the proxy server in nginx('get', 'http://:81/?user=admin', true);
();

// 
var http = require('http');
var server = ();
var qs = require('querystring');
('request', function(req, res) {
    var params = ((2));
    // Write cookies to the front desk    (200, {
        'Set-Cookie': 'l=a123456;Path=/;Domain=;HttpOnly'   // HttpOnly: The script cannot be read    });
    ((params));
    ();
});
('8080');
('Server is running at port 8080...');

The above is the detailed explanation of the method of php to solve cross-domain problems. For more information about php to solve cross-domain problems, please pay attention to my other related articles!