Dev.to Security 🔐 Cybersecurity 👁 0 📖 2 min read

PHP Sessions Not Working? 5 Mistakes That Break Your Login (and the Fix for Each)

You log in, it works, and the very next page forgets who you are. Or the login page throws 'headers already sent' before it does anything at all. PHP sessions are simple once you understand them, but they punish small mi

You log in, it works, and the very next page forgets who you are. Or the login page throws 'headers already sent' before it does anything at all. PHP sessions are simple once you understand them, but they punish small mistakes hard. Here are the five I see most often, and the fix for each.

  1. Output before session_start(). A session cookie is sent as an HTTP header, and headers cannot go out after the body starts. A single space before <?php, a blank line, or an echo in an included file is enough to break it. Put session_start() on the very first line of the file, before anything else, and save your files without a BOM.

  2. Forgetting session_start() on one page. Each page is independent. The login page starts the session, the dashboard never does, and suddenly $_SESSION is empty on the dashboard even though the session itself is fine. Every page that reads session data needs the call. If login works and the next page forgets you, check this first.

  3. Half-finished logout. Deleting one key is not logging out. If you only unset() the user ID, the session file and the cookie are still alive, and the next person on a shared computer can walk straight back into the account. A real logout does all three: clear $_SESSION, delete the cookie with setcookie(), and call session_destroy().

  4. Never regenerating the session ID. When a user logs in, their session ID should change. If it does not, anyone who learned the pre-login ID can ride it into the logged-in account — a session fixation attack. One line fixes it: session_regenerate_id(true) right after the password check passes.

  5. No idle timeout. Sessions do not expire just because the user walked away. Store $_SESSION['last_activity'] = time() on every request, and on protected pages destroy the session when the gap passes your limit — 30 minutes is a sane default.

One more habit: never store a password or a password hash in the session. Keep the user ID and a display name there, and look everything else up fresh from the database.

I wrote the full guide with a complete MySQL login example, a protected-page pattern, and the secure cookie settings here: https://rajadevsolutions.online/blog/how-to-use-php-sessions

It covers session_start(), $_SESSION, logout, idle timeouts, and the difference between sessions, cookies, and tokens — with working code for every step.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.