Session will keep the modal from reappearing during the remainder of time the client has their browser open or until the session is expired/closed on the server side (short-term). A cookie will keep the modal from reappearing as long as the cookie is not deleted from their computer (long-term)
Here is how I would do it using a bootstrap modal and cookies:
- Check if the cookie exists already.
- If the cookie doesn't exist, run the modal.
- Once the modal is acknowledged, store a cookie on the client's machine.
header.php
if (isset($_POST['btn_modal'])) {
$nameofCookie = $_POST['btn_modal'] . '-' . $_SERVER['REMOTE_ADDR'];
$cookieExp = (86400 * 365);
if (!array_key_exists($nameofCookie, $_COOKIE)) {
setcookie($name, '_any_value_goes_here_to_store_in_cookie', $cookieExp, '/');
header('Location: https://' . $_SERVER['HTTP_HOST'] . URI);
die();
}
}
I personally prefer to use the username if the user is logged in, but if not storing the username in a session, you can use their IP as how it's shown above. Here's with username, only one line is different.
if (isset($_POST['btn_modal'])) {
$nameofCookie = $_POST['btn_modal'] . '-' . $_SESSION['username'];
$cookieExp = (86400 * 365);
if (!array_key_exists($nameofCookie, $_COOKIE)) {
setcookie($name, '_any_value_goes_here_to_store_in_cookie', $cookieExp, '/');
header('Location: https://' . $_SERVER['HTTP_HOST'] . URI);
die();
}
}
index.php (or whatever page the modal is going on)
<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>
footer.php
if(array_key_exists($nameofCookie, $_COOKIE)) {
echo "<script>
$(window).on('load',function(){
$('#newModal').modal('show');
});
</script>";
}
The script to set the cookie must be placed in the header, and it is best if the script to check and run the modal is placed anywhere after the html code for the modal, preferably the footer.