根据 php 中的引用 URL 做一些事情

我有这个代码,它运行良好


<?php

if(strstr($_SERVER['HTTP_REFERER'], 'example.com')){

  echo 'yes'; 

  } else {

    echo 'no';

  }


?>

问题是如果访问也来自 example2.com,我如何获得肯定


我试过了,但它不工作


<?php

    if(strstr($_SERVER['HTTP_REFERER'], 'example.com' or 'example2.com')){

      echo 'yes'; 

      } else {

        echo 'no';

      }


    ?>

有解决办法吗?


饮歌长啸
浏览 150回答 1
1回答

蓝山帝景

一种简单的方法是创建一个允许值的数组,并使用循环。创建一个布尔值,说明用户是否来自允许的站点,将其默认设置为 false。在遍历允许的站点时,如果引用者匹配任何允许的站点,则将此布尔值更改为 true。$allowed_sites = ['example.com', 'example2.com'];$referrer_is_allowed = false;foreach($allowed_sites as $url) {&nbsp; &nbsp; if(strstr($_SERVER['HTTP_REFERER'], $url)) {&nbsp; &nbsp; &nbsp; &nbsp; $referrer_is_allowed = true;&nbsp; &nbsp; }}echo $referrer_is_allowed ? 'yes' : 'no';请记住,这并不能保证任何特定用户实际上来自HTTP_REFERER您正在检查的用户,原因有几个。$_SERVER['HTTP_REFERER']很容易被欺骗,并且不能真正信任安全性。诸如此类的引用者site_not_allowed.com/example.com仍会通过此检查。您至少可以通过检查引荐来源网站是否以允许的网站开头来保护自己免受第二个问题的影响,如下所示:foreach($allowed_sites as $url) {&nbsp; &nbsp; $referrer = str_replace(['http://', 'https://'], ['',''], $_SERVER['HTTP_REFERER']);&nbsp; &nbsp; if(substr($referrer, 0, strlen($url)) === $url) {&nbsp; &nbsp; &nbsp; &nbsp; $referrer_is_allowed = true;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP