在客户端打开浏览器的剩余时间内,或直到会话在服务器端过期/关闭(短期),会话将阻止模式再次出现。只要 cookie 没有从他们的计算机中删除(长期),cookie 就会阻止模态再次出现
以下是我使用引导模式和 cookie 的方法:
- 检查 cookie 是否已经存在。
- 如果 cookie 不存在,请运行模式。
- 确认模式后,在客户端计算机上存储一个 cookie。
header.php
# check if "Got-It!" button has been pressed
if (isset($_POST['btn_modal'])) {
$nameofCookie = $_POST['btn_modal'] . '-' . $_SERVER['REMOTE_ADDR']; // store name of modal with client's IP for the cookie's name
$cookieExp = (86400 * 365); // time in seconds for cookie to expire
# check if this cookie exists already
if (!array_key_exists($nameofCookie, $_COOKIE)) {
setcookie($name, '_any_value_goes_here_to_store_in_cookie', $cookieExp, '/'); // create cookie
header('Location: https://' . $_SERVER['HTTP_HOST'] . URI); // refresh the current page after they click "Got It!"
die();
}
}
如果用户已登录,我个人更喜欢使用用户名,但如果不在会话中存储用户名,您可以使用他们的 IP,如上所示。这里是用户名,只有一行不同。
# check if "Got-It!" button has been pressed
if (isset($_POST['btn_modal'])) {
$nameofCookie = $_POST['btn_modal'] . '-' . $_SESSION['username']; // store name of modal with client's username for the cookie's name
$cookieExp = (86400 * 365); // time in seconds for cookie to expire
# check if this cookie exists already
if (!array_key_exists($nameofCookie, $_COOKIE)) {
setcookie($name, '_any_value_goes_here_to_store_in_cookie', $cookieExp, '/'); // create cookie
header('Location: https://' . $_SERVER['HTTP_HOST'] . URI); // refresh the current page after they click "Got It!"
die();
}
}
index.php(或模式正在运行的任何页面)
<!-- code... -->
<!-- begin: What's New? [Modal] -->
<div class="modal fade" id="newModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">What's new</h5>
</div>
<div class="modal-body">
<ul>
<li>NEW THIS</li>
<li>NEW THAT</li>
<li>NEW EVERYTHING</li>
</ul>
</div>
<div class="modal-footer">
<form method="post" action="<?=$_SERVER['REQUEST_URI'];?>">
<button type="submit" class="btn btn-primary" name="btn_modal" value="newModal">Got It!</button>
</form>
</div>
</div>
</div>
</div>
<!-- end: What's New? [Modal] -->
<!-- more code... ->
footer.php
if(array_key_exists($nameofCookie, $_COOKIE)) {
echo "<script>
$(window).on('load',function(){
$('#newModal').modal('show');
});
</script>";
}
设置cookie的脚本必须放在页眉中,最好将检查和运行模态的脚本放在模态的html代码之后的任何位置,最好是页脚。