Best solution to the Cross-domain problem of PHP Ajax


发布时间 : 2022-11-04 02:00:04 UTC

This article implements cross domain by setting Access Control Allow Origin.

For example, the domain name of the client is client.runoob.com, and the requested domain name is server.runoob.com. If you directly use ajax access, the following errors will occur:

XMLHttpRequest cannot load http://server.voidme.com/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin' http://client.voidme.com' is therefore not allowed access.

PHP Ajax

1. Allow access to a single domain name

Specify a domain name( http://client.runoob.com )cross domain access, you only need to add the following code to the file header(http://server.runoob.com/server.php):

Header ('Access-Control-Allow-Origin: http://client.voidme.com');

2. Allow multiple domain names to access

Specify multiple domain names(http://client1.runoob.com、http://client2.runoob.com) cross domain access, you only need to add the following code to the file header (http://server.runoob.com/server.php):

$origin = isset ($_ SERVER ['HTTP_ORIGIN']) ? $_ SERVER ['HTTP_ORIGIN']:''

$allow_origin = array (
    'http://client1.voidme.com',
    'http://client2.voidme.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, simply add the following code to the header of the http://server.voidme.com/server.php file:

Header ('Access-Control-Allow-Origin:*')