Skip to content
PHP Logo

Is building a user-specific history in the session a better alternative to using meta data for page redirection in PHP?

When dealing with page redirection in PHP, using a user-specific history in the session can provide a more personalized and efficient way to redirect users based on their previous actions. This approach allows for a more dynamic and context-aware redirection compared to using static meta data. Storing user-specific history in the session can help create a more seamless browsing experience for users.

php
session_start();

// Add the current page to the user's history
if(!isset($_SESSION['history'])) {
    $_SESSION['history'] = [];
}
array_push($_SESSION['history'], $_SERVER['REQUEST_URI']);

// Redirect user based on their history
if(count($_SESSION['history']) >= 2) {
    $previousPage = $_SESSION['history'][count($_SESSION['history']) - 2];
    
    // Perform redirection based on the previous page
    if($previousPage == 'somepage.php') {
        header('Location: anotherpage.php');
        exit();
    }
}