How to realize cross-domain request by php
This article is about how php implements cross-domain requests. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
How php implements cross-domain requests: we can allow access to all domain names by setting [header ('Access-Control-Allow-Origin:*');].
This article operating environment: windows10 system, php 7, thinkpad T480 computer.
If we need to implement cross-domain in PHP, we can do so by setting Access-Control-Allow-Origin. Next, let's give an example to facilitate your better understanding.
Suppose the client domain name is client.runoob.com and the requested domain name is server.runoob.com.
If we use ajax access directly, the following error occurs:
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.
Allow access to a single domain name
If you 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');
Allow multiple domain names to access
To specify cross-domain access for multiple domain names (http://client1.runoob.com, http://client2.runoob.com, etc.), you only need to add the following code to the header of the http://server.runoob.com/server.php file:
$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);}
Allow all domain names to access
To allow all domain names to access, simply add the following code to the header of the http://server.runoob.com/server.php file:
Header ('Access-Control-Allow-Origin:*'); Thank you for reading! This is the end of the article on "how to implement cross-domain requests in php". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!