【问题标题】:WordPress check if Sec-GPC value exists in HTTP Request HeaderWordPress 检查 HTTP 请求标头中是否存在 Sec-GPC 值
【发布时间】:2022-12-29 06:20:14
【问题描述】:

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

    <?PHP function detect_gpc_signal() {
    if (isset($_GET['Sec-Gpc'])) {
      echo 'GPC signal detected in GET data';
    } elseif (isset($_POST['Sec-Gpc'])) {
      echo 'GPC signal detected in POST data';
    } elseif (isset($_COOKIE['Sec-Gpc'])) {
      echo 'GPC signal detected in COOKIE data';
    } elseif (isset($_SERVER['Sec-Gpc'])) {
      echo 'GPC signal detected in SERVER data';
    } else {
      echo 'No GPC signal detected';
    }
} 
add_action('wp_footer', 'detect_gpc_signal'); ?>

【问题讨论】:

  • 您可以尝试使用 getallheaders(),然后检查 issetempty 以获取特定的标头密钥。
  • 或者类似的 $request->get_header('Sec-Gpc'), read more

标签: php wordpress http-headers


【解决方案1】:

感谢您建议 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' );

【讨论】:

    猜你喜欢
    • 2021-04-10
    • 1970-01-01
    • 2017-11-13
    • 2021-05-28
    • 2016-06-29
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    相关资源
    最近更新 更多