Home > Backend Development > PHP Problem > How to set php to be cross-domain

How to set php to be cross-domain

王林
Release: 2023-03-11 10:08:01
Original
20045 people have browsed it

The way to set php to be cross-domain is to add the [header("Access-Control-Allow-Origin: *");] statement directly to the header of the php file, so that all addresses can be allowed to cross-domain requests. .

How to set php to be cross-domain

The operating environment of this article: windows10 system, php 7.3, thinkpad t480 computer.

There are three ways to set up PHP to allow cross-domain access. The specific methods are as follows:

Method one:

header("Access-Control-Allow-Origin: *");//允许所有地址跨域请求
Copy after login

Method two:

header("Access-Control-Allow-Origin: http://localhost:8080");//指定某个地址可以跨域请求,这里只能指定一个
Copy after login

Method 3: If you want to allow cross-domain requests from multiple addresses, you can write like this

$origin = ['http://localhost:8080','http://localhost:8081'];
$AllowOrigin = 'http://localhost:8080';
if(in_array($_SERVER["HTTP_ORIGIN"],$origin))
{
    $AllowOrigin = $_SERVER["HTTP_ORIGIN"];
}
header("Access-Control-Allow-Origin: ".$AllowOrigin );
Copy after login

Set the allowed request methods, you can use * to indicate all, header("Access-Control-Allow -Methods: POST");

If the request is allowed to carry cookies, the origin configuration cannot use * at this time. At this time, the front end seems to also need to be configured so that the request carries cookie header('Access-Control-Allow-Credentials :true');

Set to allow cross-domain request headers. Login verification information is usually added to the request header. Then the server needs to specify which request headers are allowed. * cannot be used here. Use commas for multiple fields. separated. header('Access-Control-Allow-Headers:token');

Related recommendations:php video tutorial

The above is the detailed content of How to set php to be cross-domain. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template