Hey everyone! I’m working on an online store and I’ve got a small issue. I made a login page that works fine, but when users log in and go to the home page, their user ID doesn’t come along for the ride. This is a problem because I want to show a cart icon only for logged-in users.
Here’s what I’ve got so far:
function loginUser(username, password) {
$.ajax({
url: '/api/login.php',
method: 'POST',
data: { action: 'signin', user: username, pass: password },
success: function(data) {
var result = JSON.parse(data);
if (result.ok) {
showMessage('Welcome back!', 'success');
setTimeout(function() {
window.location.href = '/home';
}, 2000);
} else {
showMessage(result.error, 'error');
}
},
error: function() {
showMessage('Network error. Try again later.', 'error');
}
});
}
This gets users logged in, but on the home page, I can’t tell if they’re actually logged in or not. I want to show a cart icon like this:
<?php
if ($userLoggedIn) {
echo '<a href="/cart" class="cart-icon"><i class="fa fa-shopping-cart"></i> <span class="item-count">0</span></a>';
} else {
echo '';
}
?>
Any ideas on how to pass the user info to the home page after login? Thanks in advance!
Hey Isaac_Stargazer! Interesting problem you’ve got there. Have you considered using cookies instead of sessions? They can be pretty handy for this kind of thing.
Here’s a thought - what if you set a cookie when the user logs in? Something like this in your login.php:
setcookie('user_logged_in', 'true', time() + (86400 * 30), '/');
Then on your home page, you could check for the cookie:
$userLoggedIn = isset($_COOKIE['user_logged_in']) && $_COOKIE['user_logged_in'] === 'true';
This way, you don’t have to worry about starting sessions on every page. Plus, cookies can persist even after the browser is closed, which might be nice for user experience.
What do you think about this approach? Have you tried anything like this before? I’m curious to hear if you’ve explored other options too!
I encountered a similar issue in my project. The solution lies in utilizing PHP sessions. After successful login, set a session variable in your login.php file:
session_start();
$_SESSION['user_id'] = $userId;
On your home page, check for this session variable:
session_start();
$userLoggedIn = isset($_SESSION['user_id']);
This approach maintains the user’s login state across pages. Remember to include session_start() at the beginning of each PHP file where you need to access session data. Also, consider implementing a logout mechanism to destroy the session when the user logs out.
hey isaac, i’ve dealt with this before. you need to set a session variable when the user logs in. in your login.php, add this after successful login:
$_SESSION['user_id'] = $userId;
then on your home page, check for the session:
session_start();
$userLoggedIn = isset($_SESSION['user_id']);
that should do the trick for ya!