Home > Article > Backend Development > How to set php to be cross-domain
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. .
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: *");//允许所有地址跨域请求
Method two:
header("Access-Control-Allow-Origin: http://localhost:8080");//指定某个地址可以跨域请求,这里只能指定一个
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 );
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!