开发者

Show / hide div with sessions or cookie

开发者 https://www.devze.com 2023-02-22 05:52 出处:网络
I need to hide or show a div that have a slideshow inside. The idea is to give to the users a link for them to hide or show the div.

I need to hide or show a div that have a slideshow inside. The idea is to give to the users a link for them to hide or show the div.

At the moment I call the slideshow on the body of the page with <?php include('slideshow.php'); ?>

After the user clicks on the link to hide/show the div I will like to call a second file ( <?php include('no-slideshow.php'); ?开发者_StackOverflow> ) which contain a diferent div.

As far as I had found there is no way to achieve this with sessions, or at least I did't find a solution to this problem.

My guess is that this need to be done with cookies, but I don't understend how.


If you don't want to use JavaScript only way to achieve that is to use link (requires page to be reloaded).

This is basic logic only, not a complete solution, but think you'll get the point.

Create a link on web page to the server-side script.

<a href="toggle_visibility.php">hide/show</a>

Create script togle_visibility.php to process user's request.

<?php

  $hidediv = isset($_COOKIE['hide_div']) && ($_COOKIE['hide_div'] == 'hide');
  $cookie_value = !$hidediv ? 'hide' : 'show';
  setcookie('hide_div', $cookie_value, time()+32000000); // cookie expires after year
  header('location: http://www.mysite.com/index.php');

?>

All you need now (after return to original page) is to check value stored in cookie and decide do you want od not to show that div to do user.

<?php

  ... more code

  $hidediv = isset($_COOKIE['hide_div']) && ($_COOKIE['hide_div'] == 'hide');
  if ($hidediv) {
    include('no-slideshow.php');
    }
  else {
    include('slideshow.php');
    }

  ... more code 

?>

EDIT: $hidediv condition.

It works if user has JavaScript disabled but doesn't work if cookies has been disabled in browser settings.

I did not check this code, so same typos are possible.


I am not sure I understood. You want to hide div once user cliks on a link?

Why are you not doing this using javascript? (hide/show the divs?)


This command will set a cookie named include with value what to include.

setcookie('include', 'what to include', time()+86400);

You can check this cookie before include like this:

if (isset($_COOKIE['include'])) {
    include($_COOKIE['include'] . '.php');
} else {
    include('slideshow.php');
}

Note: because cookies can be easily faked you'll need to check twice what to include.

0

精彩评论

暂无评论...
验证码 换一张
取 消