搜索

首页  >  问答  >  正文

检查WordPress中HTTP请求头中是否存在Sec-GPC值

如何检测HTTP请求标头中是否存在“Sec-GPC:1”?

P粉930534280P粉930534280455 天前588

全部回复(1)我来回复

  • P粉311464935

    P粉3114649352023-09-01 11:03:53

    感谢您建议 getallheaders()。在你的帮助下,我找到了两种方法,使用和不使用 Javascript。

    /* Add GPC Banner to WP Header */
    function display_gpc_signal_banner() {
    echo '<section id="headerBannerGpc" class="bg-color"><div 
    class="container detect-gpc-signal py-1 small"><span class="alert- 
    circle"></span> Global Privacy Signal Detected</div></section>';
    }
    add_action('wp_head', 'display_gpc_signal_banner');
    
    // Detect GPC Signal with Javascript
    function detect_gpc_signal_js() {
    ?>
      <script>
      if(navigator.globalPrivacyControl == true ) {
        // Add a class to the body tag -- This makes the GPC banner visible
        document.body.classList.add('gpc-signal-detected');
        document.getElementById('headerBannerGpc').style.display = "block";
      } else {
        // Add a class to body tag declaring the GPC signal was not detected
        document.body.classList.add('no-gpc-signal-detected');
        document.getElementById('headerBannerGpc').style.display = "none";
      }
      </script>
      <?
    }
    add_action('wp_footer', 'detect_gpc_signal_js');
    
    // Add a unique class to the body tag when GPC signal is detected
    function detect_gpc_signal_body_class( $classes ) {
    $headers = getallheaders();
    if($headers['sec-gpc'] == 1) {
      $classes[] = 'gpc-signal-detected-no-js';
    } else {
      $classes[] = 'no-gpc-signal-detected-no-js';
    }
    return $classes;
    }
    add_filter( 'body_class', 'detect_gpc_signal_body_class' );

    更新

    当将 HTTP_ 添加到值中时,原始函数将起作用。

    if (isset($_GET['HTTP_SEC_GPC'])) {
      echo 'GPC signal detected in GET data';
      } elseif (isset($_POST['HTTP_SEC_GPC'])) {
      echo 'GPC signal detected in POST data';
      } elseif (isset($_COOKIE['HTTP_SEC_GPC'])) {
      echo 'GPC signal detected in COOKIE data';
      } elseif (isset($_SERVER['HTTP_SEC_GPC'])) {
      echo 'GPC signal detected in SERVER data';
      } else {
       echo 'No GPC signal detected';
      }

    回复
    0
  • 取消回复