How to add visited pages urls into a session array?

前端 未结 3 719
北荒
北荒 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:30

    You've ommitted session_start();. Working code (without trimming):

    <?php
    session_start();
    $currentpageurl = $_GET['username'];
    $_SESSION['pageurl'][] = $currentpageurl;
    
    foreach($_SESSION['pageurl'] as $key=>$value) {
        echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
    }
    ?>
    
    0 讨论(0)
  • 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']);
    
    0 讨论(0)
  • 2021-01-23 07:54

    You are always overwriting the array with a new one here:

    $urlarray=array();       // new empty array
    $urlarray[] = $currentpageurl;    
    $_SESSION['pageurl']=$urlarray;
    

    Instead use:

    session_start();
    // like @Kwpolska said, you probably miss that, so $_SESSION didnt work
    
    is_array($_SESSION["pageurl"]) or $_SESSION["pageurl"] = array();
    // fix for your current problem
    
    $_SESSION['pageurl'][] = $currentpageurl;
    // This appends it right onto an array.
    
    $_SESSION["pageurl"] = array_slice($_SESSION["pageurl"], -10);
    // to cut it down to the last 10 elements
    
    0 讨论(0)
提交回复
热议问题