Home > Article > Backend Development > How to implement cross-domain requests in php
How to implement cross-domain requests in php: You can allow access to all domain names by setting [header('Access-Control-Allow-Origin:*');].
The operating environment of this article: windows10 system, php 7, thinkpad t480 computer.
In PHP, if we need to implement cross-domain, we can do it by setting Access-Control-Allow-Origin. Next, let’s give an example to help everyone understand better.
Assume that the current client domain name is client.runoob.com, and the requested domain name is server.runoob.com.
If we use ajax to access directly, the following error will occur:
XMLHttpRequest cannot load http://server.runoob.com/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://client.runoob.com' is therefore not allowed access.
1. Allow a single domain name to access
Specify a domain name (http://client.runoob. com) for cross-domain access, you only need to add the following code to the header of the http://server.runoob.com/server.php file:
header('Access-Control-Allow-Origin:http://client.runoob.com');
2. Allow multiple domain names to access
To specify multiple domain names (http://client1.runoob.com, http://client2.runoob.com, etc.) for cross-domain access, you only need to add the file header at http://server.runoob.com/server.php Add the following code:
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : ''; $allow_origin = array( 'http://client1.runoob.com', 'http://client2.runoob.com' ); if(in_array($origin, $allow_origin)){ header('Access-Control-Allow-Origin:'.$origin); }
3. Allow all domain names to access
To allow all domain names to access, just add the file header at http://server.runoob.com/server.php Add the following code:
header('Access-Control-Allow-Origin:*');
Recommended learning: php training
The above is the detailed content of How to implement cross-domain requests in php. For more information, please follow other related articles on the PHP Chinese website!