Home >Backend Development >PHP Problem >How to crack the ban on cross-domain access in php
Cross-domain refers to requesting resources from another domain name from a web page in one domain name. For example, request the resources of www.google.com from the www.baidu.com page. The stricter definition of cross-domain is: as long as the protocol, domain name, and port are different, it is regarded as cross-domain.
If a web page can freely access the resources of another website, then security problems may occur without the customer's complete knowledge, so the default is Cross-domain access is not allowed.
In addition, cross-domain access configuration needs to be allowed, is as follows (no other output operations are allowed before configuring the content): (Recommended learning: PHP programming From entry to master)
//设置允许跨域的 请求源地址 //方式一: header("Access-Control-Allow-Origin: *");//允许所有地址跨域请求 //方式二: header("Access-Control-Allow-Origin: http://localhost:8080");//指定某个地址可以跨域请求,这里只能指定一个 //方式三:如果要允许多个地址跨域请求可以这样写 $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 ); --------------------------------------------------------------------------------- //设置允许的请求方法,可以用*表示所有, header("Access-Control-Allow-Methods: POST"); --------------------------------------------------------------------------------- //如果允许请求携带cookie,此时 origin配置不能用 *,此时前端似乎也要做配置,让请求中携带cookie header('Access-Control-Allow-Credentials:true'); --------------------------------------------------------------------------------- //设置允许跨域的请求头,通常会在请求头里面加登录验证信息,那么服务端需要指定允许那些请求头,这里不能用*,多个字段用逗号隔开。 header('Access-Control-Allow-Headers:token');
The above is the detailed content of How to crack the ban on cross-domain access in php. For more information, please follow other related articles on the PHP Chinese website!