[英]Set Cookie with htaccess
我在Apache服务器上使用WordPress并且想在有人第一次登陆我的网站时使用我的.htaccess设置 cookie。
如果可能的话,我会将两个Cookies 设置为:
通常在 PHP 中,我只需要:
function set_user_cookie() {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if (!isset($_COOKIE['LandingPageURL'])) {
setcookie('LandingPageURL', $url, time()+2678400, "/");
}
}
add_action( 'init', 'set_user_cookie');
但是我们一直注意到缓存问题,所以我想知道是否可以在我的.htaccess中实现这一点。
示例 URL: www.example.com/ ?teamname=Chicago+Bulls
你可以使用这样的东西。 这会将完整的 URL 存储在名为 LandingPageURL 的 cookie 中。
RewriteEngine On
RewriteBase /
// if the cookie "LandingPageURL" is not set
RewriteCond %{HTTP_COOKIE} !^.*LandingPageURL.*$ [NC]
// then set it ...
RewriteRule ^(.*)$ - [co=LandingPageURL:$1:.example.com:2678400:/]
您可能想为您的 cookie 使用HttpOnly
和Secure
等选项
还有另一种方法可以在 .htaccess 中设置 cookie,如下所示:
<If "%{HTTP_COOKIE} !^.*LandingPageURL.*$">
Header edit Set-Cookie ^(.*)$ $1;SameSite=None;Secure;HttpOnly
</If>
如果您想使用 php 读取 cookie,您可以像这样使用 go
<?php
if(!isset($_COOKIE['LandingPageURL'])) {
error_log ("Cookie named 'LandingPageURL' is not set in ".__FILE__." #".__LINE__);
} else {
error_log("Cookie 'LandingPageURL' is set in ".__FILE__." #".__LINE__);
error_log("Value of Cookie is: " . $_COOKIE['LandingPageURL'] );
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.