mic*_*urk 2 php apache cookies .htaccess http-headers
我在Apache服务器上使用WordPress,并希望在有人第一次登陆我的网站时使用我的.htaccess设置 cookie。
如果可能,我会将两个Cookie设置为:
通常在 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');
Run Code Online (Sandbox Code Playgroud)
然而,我们一直注意到缓存问题,所以我想知道是否可以在我的.htaccess 中实现这一点。
你可以使用的东西像这样。这会将完整的 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:/]
Run Code Online (Sandbox Code Playgroud)
你可能想使用类似的选项HttpOnly,并Secure为您的Cookie
还有另一种在 .htaccess 中设置 cookie 的方法,如下所示:
<If "%{HTTP_COOKIE} !^.*LandingPageURL.*$">
Header edit Set-Cookie ^(.*)$ $1;SameSite=None;Secure;HttpOnly
</If>
Run Code Online (Sandbox Code Playgroud)
如果你想用 php 读取 cookie 你可以这样
<?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'] );
}
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
178 次 |
| 最近记录: |