PHP Sessions Not Working? Fix Server Issues
In this article
PHP sessions are a core feature that lets your web application remember users across page loads — login state, shopping carts, and form data all rely on them. When sessions stop working, you'll see symptoms like users being logged out immediately, variables not persisting between pages, or PHP warnings about session paths. This guide walks you through the most common causes and fixes, from simple permission errors to server configuration problems. You'll need access to your server's file system and the ability to edit PHP configuration files (php.ini) or your web server's configuration.
What You'll Need
- FTP or SSH access to your web server
- Ability to edit files like
php.ini,.htaccess, or your virtual host configuration - A text editor (like Notepad++ or VS Code)
- Access to your server's error logs (cPanel, Plesk, or command line)
Step-by-Step
- Check the session save path. The most common cause is that PHP cannot write to the directory where it stores session files. Locate the
session.save_pathdirective in yourphp.inifile. It might be commented out or set to a path that doesn't exist. A typical value is/var/lib/php/sessionson Linux orC:\Windows\Tempon Windows. If it's not set, PHP uses the system temp directory. To find the current value, create a file with<?php echo session_save_path(); ?>and open it in your browser. - Verify and fix directory permissions. The session save path must exist and be writable by the web server user (often
www-data,apache, ornobody). On Linux, runsudo mkdir -p /var/lib/php/sessionsand thensudo chown www-data:www-data /var/lib/php/sessionsandsudo chmod 700 /var/lib/php/sessions. If you're on shared hosting, you might need to set a custom path in your.htaccessfile:php_value session.save_path "/home/yourusername/sessions"and create that folder with writable permissions (e.g., 755 or 777). - Check the session cookie settings. If the session cookie is not being sent or accepted, sessions won't persist. In
php.ini, look atsession.cookie_secure,session.cookie_httponly, andsession.cookie_samesite. If your site uses HTTPS,cookie_secureshould beOn; if it's On and you're on HTTP, sessions will break. Also, ensuresession.use_cookiesis set to1andsession.use_only_cookiesis1(recommended). If you're behind a reverse proxy or load balancer, the cookie domain might be wrong – setsession.cookie_domainto your domain (e.g.,.example.comfor subdomains). - Test with a minimal script. Create a simple PHP file with
session_start(); $_SESSION['test'] = 'hello'; echo 'Session set';and another that reads it. If the first page sets and the second shows nothing, the issue is likely the save path or cookie. If you get a warning like "Failed to write session data", it's definitely a permissions or path issue. - Clear your browser's cookies and cache. Sometimes the problem is on the client side. Old or corrupt cookies for your domain can prevent new session cookies from being stored. Ask the user to clear cookies, or test in an incognito/private window.
- Check for output before session_start(). PHP's
session_start()must be called before any HTML output, including whitespace or BOM (byte order mark) in files. If you see "headers already sent" warnings, that's the cause. Remove any spaces before<?phpand ensure no UTF-8 BOM is present in your files. Also, if you have a file that includes a session_start() after output, fix the order. - Review your web server configuration. If you're using Nginx or Apache with PHP-FPM, ensure the
session.save_pathin the PHP-FPM pool configuration matches the one in php.ini. Sometimes the pool config overrides it. Also, check that theclear_envdirective in PHP-FPM is set tonoif you rely on environment variables for session settings. - Restart PHP-FPM or Apache. After making changes to php.ini or pool configs, you must restart the PHP service for changes to take effect. Use
sudo systemctl restart php-fpmorsudo systemctl restart apache2(orhttpd). On shared hosting, you might need to contact support. - Check for session locking issues. If you have long-running requests or concurrent AJAX calls, PHP's default file-based sessions lock the session file, causing other requests to wait. This can appear as sessions "not working" when they're just blocked. You can use
session_write_close()after you're done with session data to release the lock early. - Verify session.gc_maxlifetime. If sessions expire too quickly, it might seem like they're not working. The default is usually 1440 seconds (24 minutes). Increase it if needed, but remember that garbage collection is probabilistic – the
session.gc_probabilityandsession.gc_divisorsettings control how often cleanup runs. If the session directory is shared across multiple sites, one site's garbage collection could delete another's sessions.
Common Mistakes
- Wrong permissions on session directory. Setting 777 is often a quick fix but insecure; use 700 or 750 with the correct owner.
- Forgetting to restart the web server. PHP settings changes don't apply until you restart PHP-FPM or Apache.
- Using a relative path for session.save_path. Always use an absolute path like
/var/lib/php/sessions. - Calling session_start() multiple times. This can cause warnings and unexpected behavior. Use
session_status()to check if already started. - Ignoring the error log. The exact error message often tells you exactly what's wrong.
Tips
- Use a dedicated session directory per site. This prevents cross-site interference and makes permissions easier to manage.
- Set session.cookie_httponly to 1 to prevent JavaScript from accessing the session cookie, improving security.
- For high-traffic sites, consider using a different session handler like Redis or Memcached, which are faster and support locking better.
- Always call session_start() at the top of your script, before any HTML output.
- Regularly clean up the session directory manually if you change gc settings, to avoid disk space issues.
Troubleshooting
If you've followed the steps and sessions still don't work, try these checks:
- Check the error log. Look for lines containing "session" or the path to your session files. Common messages include "open(/var/lib/php/sessions/sess_..., O_RDWR) failed: Permission denied" – that points directly to permissions.
- Verify the session ID is being sent. In your browser's developer tools (Network tab), look at the request headers. You should see a
Cookie: PHPSESSID=...header. If not, the cookie isn't being set. If it is, but the next request doesn't send it, the cookie might be rejected due to domain or path settings. - Test with a different browser or incognito mode. This eliminates client-side cookie issues.
- Disable opcode caching temporarily. Some opcode caches (like OPcache) can cause stale session files if misconfigured, though this is rare. Try disabling it in php.ini (
opcache.enable=0) and restart. - Check for a custom session handler. If your code or a framework (like Laravel or Symfony) uses a custom session driver (database, Redis), the issue might be there. Check the framework's configuration and logs.
- If you're on shared hosting, contact your host. They might have a specific requirement for session paths or have disabled certain functions.
Frequently Asked Questions
Why do my sessions work on localhost but not on the live server?
Most often it's a permissions issue on the live server's session directory. Local development (like XAMPP) often has permissive settings, while production servers are stricter. Check the save path and permissions on the server.
What does "Cannot send session cookie - headers already sent" mean?
It means PHP tried to send the session cookie after output (HTML, text, or even a space) was already sent to the browser. Move session_start() to the very top of your script, before any output, and ensure no BOM or whitespace before <?php.
How do I change the session save path in .htaccess?
You can use php_value session.save_path "/path/to/dir" in your .htaccess file, but this only works if PHP is running as an Apache module (mod_php). On PHP-FPM or CGI, use a .user.ini file in your public_html with session.save_path = "/path/to/dir".
Why do sessions expire too quickly?
Check session.gc_maxlifetime in php.ini (default 1440 seconds). Also, if your session directory is shared with other sites, their garbage collection might delete your sessions. Set a unique save path for your site.
Can I store sessions in a database instead of files?
Yes, you can implement a custom session handler using session_set_save_handler(). This is useful for scaling across multiple servers. Many frameworks provide built-in database session drivers.
What is session fixation and how does it relate to this?
Session fixation is an attack where a hacker sets a known session ID for a user. To prevent it, use session_regenerate_id(true) after login. This doesn't fix broken sessions, but it's a security best practice that can prevent session-related issues.