Redirect to Referer URL in CodeIgniter: Handling Query Strings
The core challenge you are facing isn't a limitation of CodeIgniter's session or redirect capabilities; it is how the HTTP_REFERER header is constructed and parsed. When you receive an email notification like "Click here" with the URL http://example.com/project/pm/view_conversation?id=11, that specific string needs to survive the authentication barrier intact.
Your current implementation in the base controller attempts to strip the base path using str_replace(base_url(), '', $_SERVER['HTTP_REFERER']). While this logic seems sound at first glance, it is fragile and prone to errors regarding query strings. The issue you are experiencingâwhere the id=11 portion disappearsâis almost certainly due to one of two factors: either your base URL configuration includes a trailing slash while the referer does not (causing a mismatch in the string replacement), or, more likely, the logic is inadvertently truncating the string before the query parameter begins.
Why str_replace Fails Here
Using str_replace for path manipulation is generally discouraged in modern PHP development because it operates on the entire string as a blob rather than respecting URL structure. If your base URL is defined as http://example.com/project and the referer is http://example.com/project/pm/view_conversation?id=11, a simple replace works. However, if you ever change your base URL to include a trailing slash (http://example.com/project/), the replacement fails or behaves unpredictably, often leaving artifacts like double slashes or stripping subsequent characters depending on how the regex engine handles the boundary.
Furthermore, relying solely on $_SERVER['HTTP_REFERER'] is an architectural trade-off worth noting. The referer header is not part of the standard HTTP specification; it is optional and can be stripped by privacy-focused browsers, ad blockers, or specific security configurations. If a user accesses your message link via a direct email click from a mobile device with strict privacy settings, $_SERVER['HTTP_REFERER'] might be empty or missing entirely. Your code already handles this fallback to $this->uri->uri_string(), which is correct, but that fallback will naturally point to the login page itself, creating a loop if not handled carefully.
A More Robust Implementation Strategy
To ensure the query string (the id parameter) is preserved reliably, you should avoid manual string manipulation for path stripping. Instead, leverage CodeIgniter's built-in URL helper functions or configuration constants which are version-agnostic and handle trailing slashes correctly.
Here is a refined approach using current_url() logic combined with explicit path handling:
function authenticate($type = 'user')
{
if ($type == 'user') {
// Check standard CI session key or your custom user_id variable
if (!isset($this->user_id)) {
$redirect_to = '';
if (isset($_SERVER['HTTP_REFERER'])) {
// Use base_url() with the trailing slash to match config,
// then use substr to clean the path up to the first '?' or '/'.
$full_base = base_url();
// Ensure we handle the case where referer lacks a trailing slash
if (substr($full_base, -1) !== '/') {
$full_base .= '/';
}
$redirect_to = str_replace($full_base, '', $_SERVER['HTTP_REFERER']);
// Critical: Remove leading double slashes if they exist after replacement
$redirect_to = ltrim($redirect_to, '/');
} else {
// Fallback to current URI if no referer exists
$redirect_to = $this->uri->uri_string();
}
// Ensure the redirect string starts with a slash for consistency
$final_redirect = '/' . $redirect_to;
// Pass as a GET parameter to your login controller
redirect('user/login?redirect=' . urlencode($final_redirect));
exit;
}
// ... Rest of permission checks
}
if ($type == 'admin') {
// ... Admin logic
}
}
Handling the Redirect After Login
Once the user logs in, your user_login controller needs to inspect the incoming request to determine where to send them. A simple redirect($this->input->get('redirect')) is usually sufficient, but you must validate that the target URL belongs to your application. Directly redirecting to an arbitrary string passed via GET can lead to open redirect vulnerabilities if not sanitized.
Validate the target path against a whitelist of allowed segments or ensure it starts with your base domain before performing the redirect. This pattern ensures that even if $_SERVER['HTTP_REFERER'] was malformed or missing, the user lands exactly where they intended: on the message view page with the specific conversation ID intact.
This approach moves away from brittle string replacement toward structured URL handling, ensuring that query parameters like ?id=11 are never lost in translation between the notification link and the authenticated session.