php判断请求来源地址并且限制非法来源请求
第一种：通过获取上一个页面链接来判断//获取顶级域名 function getTopHost($url){ $url = strtolower($url); //首先转成小写 $hosts = parse_url($url); $host = $hosts['host']; //查看是几级域名 $data = explode('.', $host); $n = count($data); //判断是否是双后缀 $preg = '/[\w].+\.(com|net|org|gov|edu)\.cn$/'; if(($n > 2) && preg_match($preg,$host)){ //双后缀取后3位 $host = $data[$n-3].'.'.$data[$n-2].'.'.$data[$n-1]; }else if($n > 1){ //非双后缀取后两位 $host = $data[$n-2].'.'.$data[$n-1]; } return $host; } $strUrl = isset($_SERVER['HTTP_REFERER']) ? trim($_SERVER['HTTP_REFERER']) : ''; if($strUrl != ''){ $strUrl = getTopHost($strUrl); // echo $strUrl; $all_Array = ['zzwws.cn'];//允许请求的主域名，多个域名用,分开 $isContains = in_array($strUrl,$all_Array); if(!$isContains){ exit(json_encode(['code' => 0, 'msg' => '禁止请求'])); } } 第二种：设置只允许Ajax跨域访问（PHP获取无效）if(isset($_SERVER['HTTP_ORIGIN'])){ $origin = $_SERVER['HTTP_ORIGIN']; $strUrl = parse_url($origin); $allow_origin = ['localhost', 'www.zzwws.cn'];//只允许请求的域名 if (in_array($strUrl['host'], $allow_origin)) { header('Access-Control-Allow-Origin:' . $origin); } } 第三种：设置个密钥请求（适合PHP获取）if(!empty($_GET) || !empty($_POST)){ $key = '0f1VFZE47z';//密钥 if($_GET['key'] == $key || $_POST['key'] == $key){ echo json_encode(['code' => 1,'msg' => '请求成功']); }else{ exit(json_encode(['code' => 0, 'msg' => '禁止请求'])); } } 第四种：使用hieroglyphy验证请求hieroglyphy下载地址：https://zhizun.lanzoui.com/iwGb7wt7mwh<?php session_start(); if(empty($_POST)){ include 'hieroglyphy.php'; $addsalt = md5(mt_rand(0, 999) . time()); $_SESSION['addsalt'] = $addsalt; $hieroglyphy = new hieroglyphy(); $addsaltJs = $hieroglyphy->hieroglyphyString($addsalt); }else{ if(empty($_SESSION['addsalt']) || $_POST['hashsalt'] != $_SESSION['addsalt']){ exit(json_encode(['code' => 0,'msg' => '验证失败，请刷新页面重试'])); } exit(json_encode($_POST));//验证通过 } ?> Document 第五种：js生成签名，PHP验证签名（推荐）<?php if(!empty($_POST)){ $key = '密钥';//密钥 $second = 5;//每次请求有效期，单位秒 $domain = ['cs.zzwws.xyz']; if(!in_array(parse_url($_SERVER['HTTP_REFERER'])['host'],$domain)){ exit(json_encode(['code' => 0,'msg' => '禁止请求'])); } if($_POST['time'] <= time()-$second || !check_sign($_POST['param'].$_POST['time'],$_POST['sign'])){ exit(json_encode(['code' => 0,'msg' => '验证失败，请刷新页面重试'])); }else{ exit(json_encode(['code' => 1,'msg' => '验证成功'])); } } function check_sign($text,$sign) { global $key; if(empty($_SERVER['HTTP_REFERER'])){ return false; } $host = parse_url($_SERVER['HTTP_REFERER'])['host']; if($sign != md5($text.$host.$key)){ return false; }else{ return true; } } ?> Document