How to prohibit cross-domain access in php

王林
Release: 2023-03-10 13:52:01
Original
3203 people have browsed it

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.

How to prohibit cross-domain access in php

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(); }
Copy after login

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 ------------------------------------- ... }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!