How to deal with cross-domain PHP requests

There are several ways to handle cross domain requests in PHP:

  1. Set HTTP header: Allow other domain names to access the resources of the current domain name by setting response header information.
header("Access-Control-Allow-Origin: http://example.com");

The above code will allow requests from the http://example.com domain to access resources on the current domain. If you want to allow all domain names, you can set the value to *:

header("Access-Control-Allow-Origin: *");
  1. Support preflight request: When making some complex cross-domain requests, the browser will send an OPTIONS request to check whether cross-domain is allowed. The response to the OPTIONS request can be set by the following code:
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    
    
    header("Access-Control-Allow-Origin: http://example.com");
    header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type");
    exit;
}

The above code will allow POST and GET requests from http://example.com domain name, and allow to carry Content-Type header information.

  1. JSONP solves cross-domain problems: If you make cross-domain requests by dynamically loading JavaScript files, you can use JSONP technology. The PHP backend returns data in JSONP format, and the callback function is used to process the returned results at the front end.
$data = array('name' => 'John', 'age' => 25);
$jsonpData = json_encode($data);
$callback = $_GET['callback'];
echo $callback . '(' . $jsonpData . ')';

Use JavaScript to process JSONP data on the front end:

function callback(data) {
    
    
    console.log(data);
}
var script = document.createElement('script');
script.src = 'http://example.com/api?callback=callback';
document.body.appendChild(script);
  1. Use a proxy server: If the cross-domain problem cannot be solved by the above methods, you can set a proxy on the server side to forward the cross-domain request to the target server, which can be realized through the cURL library in PHP.
$url = 'http://example.com/api';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
header('Content-Type: application/json');
echo $response;

The above code will get the data from the target server and return the data as-is to the client. Please note that this method will increase the load on the server and may cause security risks, so use it with caution.

The above are several common methods for handling PHP cross-domain requests, which method to use depends on your needs and project scenarios.

Guess you like

Origin blog.csdn.net/qq_27487739/article/details/131527032