How to add visited pages urls into a session array?

前端 未结 3 718
北荒
北荒 2021-01-23 07:05

Everytime the user visit a page, the page url will be stored into an array session. I want to have 10 elements in the array only. So that 10 elements will save 10 latest visited

3条回答
  •  孤街浪徒
    2021-01-23 07:33

    Simplest way to do this and keep just the last 10 entries will be to create your initial array with the correct size (via array_fill()). Then we can push new items onto the beginning of the array and pop old items off the other end using array_unshift() and array_pop().

    session_start();
    
    // Initialise URL array with 10 entries.
    if (empty($_SESSION['pageurls'])) {
        $_SESSION['pageurls'] = array_fill(0,10,'');
    }
    
    function trackPage($url) {
        array_unshift($_SESSION['pageurls'],$url);
        array_pop($_SESSION['pageurls']);
    }
    

    Make sure the above code always runs first. Then you can pass new URLs to the array when you want. So, perhaps something like:

    trackPage($_SERVER['REQUEST_URI']);
    

提交回复
热议问题