Home >Backend Development >PHP Tutorial >PHP sets multiple domain names to allow cross-domain access

PHP sets multiple domain names to allow cross-domain access

藏色散人
藏色散人forward
2019-09-17 14:17:255131browse

Set multiple domain names for PHP language to allow cross-domain access

Server variables:

Server variables are stored in the $_SERVER array. There is a special Key value: HTTP_ORIGIN. This key will only have a value when it is cross-domain, and it will be an empty string when it comes from the same origin

Response header settings allow access to a certain domain name: access-control-allow-origin

The header function can be set to allow cross-domain access for a certain domain name, in the form of header('access_control_allow_origin:*').

Posted code:

$allow_origin = array(
    'a.baidu.com',
    'b.baidu.com',
);
//跨域访问的时候才会存在此字段
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';  
if (in_array($origin, $allow_origin)) {
    header('Access-Control-Allow-Origin:' . $origin);
} else {
    return;
}

note: When requesting the interface through the interface tool, the $_SERVER['HTTP_ORIGIN'] variable is also an empty string.

Recommended tutorial: PHP tutorial

The above is the detailed content of PHP sets multiple domain names to allow cross-domain access. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete