How to set a session variable when clicking a <a> link

How to set a session variable when clicking a <a> link

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

How to Set a Session Variable When Clicking an <a> Link

You cannot set a session variable directly from a standard HTML anchor tag like <a href="home">. That specific limitation exists because of how the HTTP protocol and browser rendering engines function together. When a user clicks a standard link, the browser immediately initiates a full page navigation request to the destination URL. The server processes that request, generates the response, and sends it back. By the time your PHP code executes $_SESSION['link'] = home;, the session data is already being populated for that specific request context, but you have no hook into the "click event" itself on the client side.

Your initial research was correct in identifying that a native click event does not trigger server-side code before the navigation occurs. However, this constraint doesn't mean the goal is unachievable; it just means you must change how the request is initiated. The standard solution involves intercepting the click using JavaScript and sending an asynchronous request (AJAX) to your backend before allowing the page to navigate.

Intercepting the Click with JavaScript

To set $_SESSION['link'] while keeping the user on the same page, you need to prevent the default navigation behavior of the link. You can achieve this by adding a JavaScript event listener to the anchor element. This listener will execute before the browser attempts to load the new URL.

Here is how the HTML structure looks with the necessary script:

<a href="#" id="nav-link" class="session-trigger">home</a>

<script>
document.getElementById('nav-link').addEventListener('click', function(event) {
    event.preventDefault(); // Stop the browser from navigating immediately
    
    // Set the session variable via a backend call
    fetch('/api/set-session?link=home', {
        method: 'POST'
    }).then(response => {
        if (response.ok) {
            // Now you can safely navigate to your intended destination
            window.location.href = "home"; 
        } else {
            console.error('Failed to set session variable');
        }
    }).catch(error => {
        console.error('Error:', error);
    });
});
</script>

In this implementation, the href attribute is set to # or a dummy value initially. The JavaScript listener catches the click and calls event.preventDefault(). This halts the immediate redirection. Instead, a fetch request (or an AJAX call) is sent to a dedicated endpoint, such as /api/set-session.

Handling the Request in PHP

The backend endpoint receives the POST request containing the link name. In this step, you can safely set the session variable because the request has reached the server and the session is active for that specific request lifecycle.

// Inside your route handling file (e.g., app/Http/Controllers/SampleController.php)
public function setSessionLink() {
    // Get the link name from the query parameter or POST data
    $linkName = $_GET['link'] ?? $_POST['link'];
    
    // Validate and sanitize the input to prevent session fixation or XSS
    if (empty($linkName)) {
        return response()->json(['error' => 'Link name is required'], 400);
    }

    // Set the session variable
    session()->put('link', $linkName);

    // Return a success response so the frontend knows to proceed
    return response()->json(['success' => true]);
}

Trade-offs and Considerations

The primary advantage of this approach is that the URL in the browser address bar does not change until after the session variable is set. This avoids the need for query strings like home.php?link=X, which you explicitly wanted to avoid. The user experience remains clean, showing only the final destination URL (home) once the redirection happens.

However, there are significant trade-offs to keep in mind. Introducing an asynchronous call adds latency. The browser must wait for the network round-trip to your API endpoint before it can redirect the user. If the server is slow or the network connection is poor, the user will experience a noticeable delay between clicking the link and seeing the content load. In high-traffic scenarios, this extra request increases server load compared to a direct GET request.

Additionally, you must ensure that your session configuration allows for concurrent requests or that the session is properly managed across these small API calls. If your application uses strict session locking or lacks proper concurrency settings, rapid clicks might result in session errors. Finally, always sanitize the $linkName variable before storing it in the session to prevent potential security issues if the input originates from untrusted sources.

If you are building a larger application where session management is complex, exploring modern PHP frameworks like Laravel can streamline these interactions. Resources such as https://laravelcompany.com often provide documentation on handling sessions and routing within that ecosystem, which can help integrate this pattern more robustly into your existing codebase.

Our network