The way PHP implements prohibiting cross-domain access is to determine the HTTP Referer. If there is no Referer or the Referer is accessed non-locally, then access is prohibited.
The operating environment of this article: windows10 system, php 7.3, thinkpad t480 computer.
We can prohibit cross-domain access in the following two ways.
Method 1: Determine HTTP Referer
HTTP Referer is part of the header. When the browser sends a request to the web server, it usually brings the Referer to tell the server that I am from Which page is linked to, the server can obtain some information for processing.
Add the judgment HTTP Referer at the beginning of the post request "file" or "function": The following is the php code, the method is the same regardless of language.
There is no Referer and it is a direct access connection. For example, http://www.a.com/ajax.php returns error
. There is a Referer, but this site is not accessed. The Referer does not include a.com domain. Return error
// 如果(没有 Referer 或者 Referer 非本地访问的)return 'error' 或 die() 程序结束 if(!isset($_SERVER['HTTP_REFERER']) || !strstr($_SERVER['HTTP_REFERER'], 'http://www.a.com/')){ echo "error"; die(); }
Method 2: Server-side prohibits cross-domain access
Nginx prohibits cross-domain access to a certain PHP file
location ~ \.php$ { ... #新增代码 start ------------------------------------- # 假设 ajax.php 文件路径是 /includes/ajax.php 和网站域名是 www.a.com # 新增一个变量 $nolocal 值为 1 set $nolocal 1; #下面开始判断,不是 POST 或者请求路径不是 ajax.php 的路径或者请求来源属于本站域名时,都设为 0 #因为 nginx 不支持多条件判断,这里用三个 if ~ if ($request_method != POST) { set $nolocal 0; } if ($request_uri != /includes/ajax.php) { set $nolocal 0; } if ($http_referer ~* "www.a.com") { set $nolocal 0; } #经过上面的筛选,值是 1 的,也就是本站外来源POST ajax.php 数据过来,直接返回 403 拒绝处理 #这样,其他来源的请求就浪费不了你的PHP进程了。 if ($nolocal) { return 403; } #新增代码 end ------------------------------------- ... }
Free learning video sharing :php video tutorial
The above is the detailed content of How to prohibit cross-domain access in php. For more information, please follow other related articles on the PHP Chinese website!