Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk10 min

How to Fix PHP Sessions Not Working on Your Web Server

A practical, layer-by-layer guide to diagnosing PHP sessions that do not persist, from session_start() and cookie attributes to save-path permissions, expiry, and load-balanced servers.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

PHP sessions usually fail at one of three boundaries: the request never starts a session correctly, the browser does not return the session-ID cookie, or the server cannot read the session record. Test those boundaries in that order. Start the session before any $_SESSION access or output, inspect the Set-Cookie response and the next request, then verify the effective save handler and storage permissions used by the web-serving PHP process.

A successful session_start() call in one request is not proof of persistence. A session works only when the same ID reaches the next request and that request can open the corresponding server-side record. The procedure below isolates each failure without guessing.

As an Amazon Associate I earn from qualifying purchases.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Start with the failure layer

Use the symptom to choose the first check, but still verify both halves of every session: the browser-held identifier and the server-held data.

Symptom Most likely layer First check
session_start() warns, or headers cannot be sent Initialization and output timing Move session setup to the beginning of the request path and inspect PHP warnings.
No PHPSESSID (or custom session cookie) in the response Cookie creation or headers Inspect the response headers and any output or redirect emitted before startup.
The cookie is set but absent from the next request Cookie attributes or browser policy Check Secure, domain, path, SameSite, and the request’s scheme and host.
The cookie returns, but values disappear Server-side storage Check the effective save handler, save path, ownership, permissions, and error log.
Works on one server but not another Deployment topology Compare runtime settings and determine whether nodes share session storage.
Sessions vanish after an apparently random period Cookie or garbage collection lifetime Compare session.cookie_lifetime and session.gc_maxlifetime.

1. Initialize the session before using it

Call session_start() before reading or writing $_SESSION. It must also run before output, including accidental whitespace, a UTF-8 byte-order mark, debug text, or an included template. PHP needs to send a Set-Cookie header when it creates or changes the session ID.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Correct ordering

<?php
// Configure the cookie first, on every request that uses the session.
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax'
]);

session_start();

$_SESSION['last_seen'] = time();

Custom cookie parameters must be applied before session_start(), and PHP’s documentation requires calling session_set_cookie_params() for every request when you rely on custom values. Put this code in the earliest common entry point, before a framework renders a response or sends a redirect.

If a framework or hosting control panel already starts sessions, do not start a second session blindly. Check session_status() and centralize the configuration so every entry point uses the same settings.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Capture startup errors instead of assuming success

<?php
error_log('session_status=' . session_status());
error_log('session_id_before=' . session_id());

$started = session_start();

error_log('session_start=' . ($started ? 'true' : 'false'));
error_log('session_id_after=' . session_id());
error_log('session_name=' . session_name());

Review the PHP-FPM, Apache, or application log for warnings. A failure caused by headers already being sent, an invalid save path, or a custom handler often appears there even when the page itself looks normal.

Prove persistence with two requests

Set a marker in one request and read it in a separate request. A single page that writes and reads $_SESSION can appear to work while never persisting anything.

<?php
session_start();

if (!isset($_SESSION['probe'])) {
    $_SESSION['probe'] = bin2hex(random_bytes(8));
    echo 'created:' . $_SESSION['probe'];
} else {
    echo 'returned:' . $_SESSION['probe'];
}

Reload the page. The second response should say returned: followed by the same value. If it says created: again, inspect the cookie exchange and server storage in the next sections.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

2. Inspect the browser cookie exchange

Open your browser’s developer tools, select the Network panel, make a request that starts the session, and inspect its response headers. You should see a Set-Cookie header containing the configured session name, normally PHPSESSID. Inspect the immediately following request and confirm that its Cookie header sends that same name and value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can perform the same check with an HTTP client that retains cookies between requests:

curl -i -c cookies.txt -b cookies.txt https://example.test/session-probe.php
curl -i -c cookies.txt -b cookies.txt https://example.test/session-probe.php

Use your real host and endpoint in place of example.test. The first response should establish a cookie; the second request should send it back. If the response sets a cookie but the client does not return it, the attributes or URL do not match.

Check each cookie attribute

Attribute What it controls Typical failure
Secure Whether the browser sends the cookie only over HTTPS. A cookie marked Secure is not sent on plain HTTP. PHP documents session.cookie_secure as restricting delivery to secure connections.
Domain Which host names may receive the cookie. A host-only cookie, or a domain that does not match the current host, is absent after a host alias or subdomain change.
Path Which URL paths receive the cookie. A cookie scoped to /app is not sent to a script under /admin.
SameSite Whether the browser sends the cookie in cross-site navigation and requests. Lax and Strict do not send the cookie on cross-domain POST requests. A flow that intentionally requires such a POST may need SameSite=None; Secure.
HttpOnly Whether browser scripts can read the cookie. It does not prevent PHP from receiving the cookie; it only blocks JavaScript access, which is normally the safer setting.

Choose the narrowest domain, path, and SameSite policy that supports the application. For a normal same-site HTTPS application, Secure, HttpOnly, and SameSite=Lax are a practical baseline. Use Strict when the application’s navigation does not require sending the cookie from external links. Use None only for a known cross-site requirement and always pair it with Secure.

Resolve HTTP, HTTPS, and host changes

Record the URL, scheme, host, and path for both requests in the test. A reverse proxy may receive HTTPS from the browser but forward HTTP to PHP; an HTTP-to-HTTPS redirect may also change which cookie rules apply. Host aliases such as www and the bare domain can produce separate host-only cookies. Configure the application and proxy so the public scheme and host are consistent, and do not mark a cookie Secure until the browser-facing endpoint is actually HTTPS.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

3. Verify server-side session persistence

The default files save handler stores one record per session under session.save_path. The PHP worker serving web requests must be able to create, read, modify, and eventually delete files there. A command-line PHP installation can use a different configuration, so inspect the runtime attached to the web request rather than relying only on php -i in a shell.

Print the effective web-runtime settings

<?php
header('Content-Type: text/plain');
echo 'PHP version: ' . PHP_VERSION . "n";
echo 'save_handler: ' . ini_get('session.save_handler') . "n";
echo 'save_path: ' . ini_get('session.save_path') . "n";
echo 'cookie_name: ' . ini_get('session.name') . "n";
echo 'cookie_lifetime: ' . ini_get('session.cookie_lifetime') . "n";
echo 'gc_maxlifetime: ' . ini_get('session.gc_maxlifetime') . "n";
echo 'gc_probability: ' . ini_get('session.gc_probability') . "n";
echo 'gc_divisor: ' . ini_get('session.gc_divisor') . "n";

Protect or remove this diagnostic endpoint after use because configuration details can help an attacker. If session.save_handler is not files, skip file inspection and troubleshoot the configured handler instead.

Check directory existence and PHP-worker access

Confirm that the displayed save path exists and is a directory. Check its owner, group, mode, filesystem mount, and available space. Test access as the account used by PHP-FPM or the web server, not as your own login account. The worker needs write permission to create records and read permission to open them on later requests.

Do not solve a write error by making the directory world-readable or world-writable. PHP warns that a world-readable directory such as a default /tmp can let other users list session files and hijack sessions. Use a dedicated directory with ownership and permissions limited to the web-service account or an appropriate private group. Also verify that mandatory access controls, container isolation, or a read-only deployment mount are not denying access.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When a custom save handler is enabled

Redis, a database, a cache service, or an application-defined handler will not create files in session.save_path. Check the handler’s connection endpoint, database or namespace, credentials, TLS settings, key prefix, timeout, and error log. Confirm that every application node can reach the same service and that records are not being deleted by a short cache policy.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

4. Make sessions work across multiple application nodes

On a single server, local file sessions are visible to every request handled by that server. Behind a load balancer, node A can create a file that node B cannot see. The browser still sends a valid session ID, but the second node treats it as a new session.

Compare effective settings on every node

Capture these values from the web runtime on each node:

  • session.save_handler and session.save_path
  • session cookie name, domain, path, Secure, HttpOnly, and SameSite settings
  • PHP version and relevant extensions
  • custom handler endpoint, namespace, and credentials

Differences can be introduced by separate php.ini files, pool-level overrides, container images, or environment variables. A browser cannot compensate for inconsistent server configuration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose a deliberate state-sharing design

  • Shared session storage: Store sessions in a common service or filesystem reachable by all nodes, with consistent serialization and locking behavior.
  • Session affinity: Configure the load balancer to keep a client on one node. This can reduce cross-node failures but creates failover and capacity limitations; it is not equivalent to shared state.
  • Application-level state: Keep durable account or workflow state in a shared database and use the session only for a small identifier. This reduces dependence on local files but requires explicit application design.

Test by sending repeated requests while recording which node answered. A session must remain readable when the load balancer changes the node, unless affinity is an intentional part of the design.

5. Explain expiry and apparent random resets

Two independent timers govern a typical session. session.cookie_lifetime controls how long the browser keeps the cookie; the default is 0, meaning until the browser closes. session.gc_maxlifetime controls how long PHP considers an unused server-side record eligible for garbage collection; the documented default is 1,440 seconds. Garbage collection also depends on session.gc_probability and session.gc_divisor.

These timers can disagree. The browser may retain an ID after the server has deleted its record, producing a fresh session with the same cookie. Conversely, the browser may discard its cookie while the server record still exists. Compare the effective values from the web runtime, then check whether another process, cache policy, deployment cleanup job, or custom handler is deleting records sooner.

When changing cookie settings, record the existing cookie’s attributes before clearing it. A stale cookie with a different path or domain can make a correct configuration appear ineffective. Clear cookies deliberately, retest in a private window, and verify the new Set-Cookie header.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

6. Apply secure settings after functionality is proven

Once the two-request persistence test succeeds, harden the session rather than weakening it to hide a configuration error. For an HTTPS-only application, enable Secure cookies; enable HttpOnly to prevent script access; select Lax or Strict SameSite behavior that matches the application’s navigation; and enable strict mode.

; php.ini or an equivalent pool-level configuration
session.cookie_secure = On
session.cookie_httponly = On
session.cookie_samesite = Lax
session.use_strict_mode = On

session.use_strict_mode prevents PHP from accepting an arbitrary well-formed session ID that has not been initialized in storage. It reduces session-fixation risk, but it does not repair an inaccessible save path or a cookie that never returns. Apply configuration consistently across nodes and restart or reload the relevant PHP service when your platform requires it.

A repeatable troubleshooting workflow

  1. Start with a clean test. Use a private browser window or a new cookie jar, note the exact HTTPS URL, host, and path, and disable extensions that modify cookies.
  2. Check initialization. Confirm that custom parameters precede session_start(), no output precedes it, and the PHP log contains no warning.
  3. Check the response. Verify a Set-Cookie header with the expected name and attributes.
  4. Check the next request. Confirm that the browser or HTTP client sends the same cookie value back to the same applicable host and path.
  5. Check persistence. Read the marker on the second request and log the session ID on both requests without exposing it to users.
  6. Check the server runtime. Inspect the effective save handler and path from a web request; verify worker permissions, storage availability, and logs.
  7. Check topology. Repeat the test while requests reach different nodes, and compare settings or shared storage.
  8. Check expiry only after the above passes. Compare cookie lifetime, garbage-collection settings, and any external cleanup policy.
  9. Harden and retest. Enable Secure, HttpOnly, an appropriate SameSite value, and strict mode, then repeat the two-request test over the production protocol.

What a successful diagnosis should show

  • The request starts the session before any output or $_SESSION access.
  • The response sets the expected session cookie.
  • The next request returns that cookie unchanged.
  • The PHP worker can read and write the configured server-side record.
  • Every node uses compatible settings and reaches the same state store, or deliberate affinity is in place.
  • Cookie and server-record lifetimes match the application’s expected behavior.

If all six conditions hold, PHP sessions are functioning; remaining problems are likely in application logic, such as overwriting a session key, calling session_regenerate_id() at an unexpected point, or clearing the session intentionally.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.