简体   繁体   English

在PHP中基于会话隐藏div

[英]Hiding a div based on session in PHP

I have a div that contains a slider when the homepage of the website is opened. 打开网站主页时,我有一个包含滑块的div。 What im trying to achieve is that when the website is opened for the first time, the slider should appear. 我试图实现的是,当首次打开网站时,应该会出现滑块。 However, if the user goes another page other than the homepage and then returns to the homepage again, the slider should not appear. 但是,如果用户转到首页以外的其他页面,然后再次返回到首页,则不应出现滑块。

Below is the code I am trying to implement: 以下是我尝试实现的代码:

<div class="homeslidermain" style="display:<?php echo empty($_SESSION['first_load']) ? 'block' : 'none'; ?>"> 
<?php putRevSlider("typewriter-effect", "homepage") ?>
</div>

You Could try something like this 您可以尝试这样的事情

// start the session 
session_start();

$bShowBanner = true;    

if(isset($_SESSION['BannerShown'])){
    $bShowBanner = false;
}else{
    $_SESSION['BannerShown'] = true;
}
?>

<div class="homeslidermain" style="display:<?php echo ($bShowBanner ? 'block' : 'none'); ?>"> 
    <?php putRevSlider("typewriter-effect", "homepage") ?>
</div>

There are several ways to achieve it, best is to check if user visiting page for first time 有几种方法可以实现,最好是检查用户是否是首次访问页面

session_start();
if(!isset($_SESSION['first_load']))
{
   $_SESSION['first_load'] = '1';
}
if(empty($_SESSION['first_load']))
{?>
   <div> 
    Slider block //  this block loads only is first load is empty
   </div>

<?php
}?>

The recommended way would be to set a cookie using setcookie() and getcookie() ( http://php.net/manual/de/features.cookies.php ). 推荐的方法是使用setcookie()getcookie()http://php.net/manual/de/features.cookies.php )设置cookie。

If you want to use the session then you are setting "first_load" incorrectly. 如果要使用会话,则设置错误的“ first_load”。 Make sure that on any page call: 确保在任何页面调用中:

session_start(); // before you do anything else 

if(!isset($_SESSION['first_load'])) // set it to true on first load

... and to false in any other case. ...并在其他情况下为假。

The only reason why this might go wrong is if you are reinitializing your session wrong. 可能会出错的唯一原因是如果您重新初始化会话错误。 Make sure you are still in the same session after switching pages. 切换页面后,请确保您仍在同一会话中。

There is no need to output the div as display:none . 无需将div输出为display:none Just output the div only when user visits the homepage for the first time. 仅在用户首次访问主页时才输出div Use the setcookie() function to remember that user already visited he homepage, but please note that you should call this function before any output. 使用setcookie()函数来记住该用户已经访问过他的主页,但是请注意,您应该在任何输出之前调用此函数。

<?php

if (empty($_COOKIE['homepage_visited'])) {
    // Remember the first visit for one year
    setcookie('homepage_visited', 1, strtotime('+1 year'));

    // Show the slider
    echo '<div class="homeslidermain">';
    putRevSlider("typewriter-effect", "homepage");
    echo '</div>';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM