DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
VGSources
Blog

WordPress Cookies and PHP Sessions Explained

WordPress uses authentication cookies to maintain login state; PHP sessions keep application data on the server. This guide covers expiration, security attributes, REST nonces, caching and safe plugin implementation.
Length9 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

WordPress normally keeps users signed in with authentication cookies, not PHP sessions. The browser stores a cookie that identifies the login, while WordPress validates it on each request. A PHP session stores application state on the server and usually gives the browser only an identifier. Use WordPress’s built-in cookie authentication for ordinary logins; add a carefully designed server-side session only when a plugin has a genuine need for temporary, per-user state.

What WordPress cookies do

A cookie is a small value that a browser saves for a site and sends back on requests matching the cookie’s domain, path and security rules. WordPress uses cookies to verify a user and maintain login state. The cookie is presented automatically, so a visitor does not have to submit a password on every page load.

As an Amazon Associate I earn from qualifying purchases.

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

Authentication cookies are bearer credentials: whoever obtains a valid value may be able to use the associated session until WordPress expires or invalidates it. A cookie should therefore be treated like a temporary key, not like harmless preferences data. Do not place passwords, API secrets or sensitive personal information directly in an unsigned client-side cookie.

WordPress’s documented cookie families

Cookie Purpose Where it matters
wordpress_[hash] Identifies an authenticated administrator session. Administration area requests.
wordpress_logged_in_[hash] Indicates that a visitor is logged in. Front-end pages and other non-administration requests.
wordpress_sec_[hash] Secure authentication cookie for HTTPS logins. Sites using the secure login path.
Settings cookies Preserve user interface and preference choices. Dashboard and other personalized settings.
Comment cookies Remember information entered into comment forms. Visitors who leave comments.
Language cookies Remember a language or localization choice. Multilingual or localized interfaces.
Test cookies Check whether the browser accepts cookies. Capability detection during login and setup.

The exact cookie name includes a hash derived from the installation’s authentication-key configuration, so it is normal for the suffix to differ between sites. Plugins may add their own cookies for preferences or integrations; those should be documented separately and given the narrowest possible scope.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

WordPress authentication cookies versus PHP sessions

Both mechanisms let a server recognize a returning browser, but they put the state in different places and have different operational consequences.

Comparison point WordPress authentication cookie Custom PHP session
Stored state The browser holds an authentication value that WordPress validates. The server holds session data; the browser normally holds only a session identifier.
Framework integration Built into WordPress login, user resolution and capability checks. Must be started, read and closed by the plugin or application.
Lifetime and renewal WordPress applies its authentication expiration rules and the Remember Me choice. The plugin defines idle and absolute timeouts and any renewal policy.
Invalidation WordPress can clear authentication cookies and invalidate its server-side user sessions. The plugin must destroy or revoke the session in its own store.
CSRF protection Cookie-authenticated state-changing requests need WordPress nonces in addition to capability checks. Cookie-based session actions need an equivalent CSRF defense.
Caching Responses that vary by login cookie must not be served from a public full-page cache. Any response that reads session state has the same cache constraint.
Horizontal scaling WordPress authentication can be validated consistently when the installation’s keys and user data are shared. All application servers need access to one shared session store or a deliberate session-affinity design.
If a bearer value is stolen The attacker may act as the user until expiration or invalidation. The attacker may use the session until its identifier expires or the server revokes it.

For a normal WordPress login, a custom PHP session duplicates work that WordPress already performs. A session becomes reasonable when a plugin needs short-lived workflow state, a multi-step transaction, a temporary server-side cart, or another data set that should never be sent to the browser. Even then, keep the data minimal and define its lifecycle explicitly.

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

How long WordPress login cookies last

WordPress’s documented default authentication expiration is two days (48 hours). Choosing Remember Me changes the default persistence to 14 days. These are defaults, not promises that every site will use the same values: code, filters, security plugins, hosting policy and explicit expiration arguments can shorten or extend them.

With Remember Me disabled, WordPress creates a browser-session cookie subject to the normal two-day authentication expiration. A browser may discard a session cookie when its window is closed, while the server-side authentication validity still has its configured maximum. With Remember Me enabled, the cookie is persistent and is intended to survive browser restarts for the configured period.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Do not describe either duration as a guarantee that a stolen cookie remains usable for exactly that long. Logging out, changing a password, revoking sessions, administrative security actions and expiration filters can invalidate it earlier. Conversely, a copied value can remain dangerous until one of those invalidation events occurs.

Using WordPress’s supported login-cookie API

When a plugin needs to authenticate a user programmatically, use wp_set_auth_cookie() rather than constructing a cookie manually:

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.
$user_id  = 123;                 // Resolve this from your validated login flow.
$remember = true;                // false uses the normal non-Remember Me behavior.
$secure   = is_ssl();            // Send the cookie only over HTTPS when available.

wp_set_auth_cookie( $user_id, $remember, $secure );

The function accepts the user ID, a Remember Me boolean and a secure-transport flag. Call it only after credentials or another trusted authentication mechanism has been validated and before output is sent, because setting a cookie requires HTTP headers. Let WordPress generate and manage the authentication values instead of inventing a parallel format.

The older wp_setcookie() API has been deprecated since WordPress 2.5.0. New plugin code should not depend on it.

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Security attributes every session needs

Authentication is only as strong as the way its identifier is transported and revoked. Apply the following controls to WordPress cookies and to any custom session cookie.

  • HTTPS and Secure: Serve the entire authenticated experience over HTTPS and set the Secure attribute so the browser does not send the identifier over cleartext HTTP. A secure flag cannot compensate for pages that still allow an attacker to downgrade or inject HTTP content.
  • HttpOnly: Mark session identifiers HttpOnly when JavaScript does not need to read them. This reduces exposure to script-based theft, although it does not stop every cross-site scripting attack or prevent a compromised page from making requests.
  • SameSite: Choose SameSite=Lax or SameSite=Strict where the site’s login and embedded-content requirements permit it. SameSite is defense in depth, not a replacement for CSRF tokens.
  • Rotation: Regenerate a custom session identifier after authentication and after privilege changes. Rotation prevents an identifier supplied before login from being reused as the authenticated session.
  • Server-side revocation: Invalidate the server-side session on logout and high-risk events such as password changes or account recovery. Removing only the browser cookie does not revoke a copied identifier.
  • Minimal data: Keep secrets and sensitive personal data in a protected server-side store. A client cookie can be read, copied and replayed by anyone who obtains it.

Why the REST API needs a nonce when you are logged in

WordPress cookie authentication is established by the normal login flow. A browser automatically attaches that cookie to a REST request, which creates a cross-site request-forgery risk: a malicious page could try to make the browser submit an action while the victim is logged in.

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

For REST requests made with cookie authentication, WordPress therefore requires a REST nonce, commonly supplied in the X-WP-Nonce header (or as an _wpnonce parameter). A request without a valid nonce is treated as unauthenticated even if the login cookie is present. The nonce proves that the request came through a page that had access to a WordPress-generated token; it is not a replacement for a password or an authorization check.

fetch( '/wp-json/example/v1/profile', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-WP-Nonce': window.exampleSettings.restNonce
    },
    body: JSON.stringify( { display_name: 'New name' } )
} );

The script must receive a nonce generated for the REST API by the authenticated WordPress page. On the server, the endpoint must still verify the intended capability, for example with its permission_callback. A valid nonce says that the request passed the CSRF check; it does not grant permission to edit another user’s data.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

When a plugin genuinely needs a PHP session

Do not call session_start() casually in a theme or plugin. Starting a session sends or changes headers, can happen too late if output has already begun, makes otherwise cacheable pages vary, and introduces a second authentication state that must be secured and invalidated.

If a session is unavoidable, design it as a small subsystem rather than adding one line to a template:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Choose the state: List exactly which temporary values need server-side storage and remove anything that can be recomputed or stored as a non-sensitive preference.
  2. Start before output: Initialize the session at an early, predictable hook before any HTML, whitespace or headers are emitted. Verify that the hosting stack and other plugins do not already own PHP session handling.
  3. Set cookie parameters first: Configure a narrow path, HTTPS-only Secure, HttpOnly and an appropriate SameSite mode before starting the session. Use an explicit lifetime instead of relying on an unlimited default.
  4. Use a server-side store: Ensure every web server can read the same session data. Local files on one node fail when a subsequent request lands on another node unless the deployment deliberately provides shared storage or session affinity.
  5. Rotate after trust changes: Call session-ID regeneration after login and privilege changes, retaining data only when the workflow requires it.
  6. Define logout and expiry: Remove the session data, expire the identifier and revoke it server-side. Add idle and absolute timeouts appropriate to the sensitivity of the workflow.
  7. Protect every state-changing action: Use WordPress nonces for WordPress-facing actions or another robust CSRF mechanism for the custom workflow, then perform capability and ownership checks.
  8. Audit caching: Mark session-dependent responses as private or otherwise exclude them from shared full-page caches. A cached response can leak one user’s state to another.

The exact PHP session configuration must be validated against the site’s PHP version, reverse proxy, object cache and deployment model. A technically correct cookie flag is still ineffective if a proxy terminates TLS incorrectly or strips the relevant header.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Cookies, sessions and page caching

Public page caches cannot safely serve one copy of a response to every visitor when the response changes according to a login cookie or session value. Exclude wp-login.php, account pages, personalized fragments and any cookie-varying response from full-page caching. Cache configuration must also avoid caching a logged-in response and replaying it to an anonymous visitor.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Static assets can usually remain cacheable, but do not embed secrets or user-specific data in a JavaScript file that is publicly cached. If a page needs a REST nonce, print or localize it in a response that is handled with the same privacy rules as the user’s authenticated page.

Troubleshooting common failures

The user is logged in but every request appears anonymous

  • Confirm the response actually sets the cookie before output and that the browser accepts it.
  • Check that the cookie domain and path match the URL making the request, and that HTTPS is used when Secure is enabled.
  • Inspect reverse-proxy or load-balancer TLS settings; a site that terminates HTTPS upstream can misreport the request as insecure.
  • Clear a stale cookie after changing salts, domains or environments, then authenticate again.

A REST request returns an authentication or nonce error

  • Send the current REST nonce in X-WP-Nonce or _wpnonce; do not assume that a login cookie alone is sufficient.
  • Ensure the page that generated the nonce is not an old cached copy.
  • After nonce validation, check the endpoint’s capability and object-ownership logic separately.

Logout appears successful but a copied session still works

Deleting a browser cookie affects that browser only. Revoke the corresponding WordPress or custom server-side session as part of logout and high-risk account events, then require a fresh authentication.

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

Enabling sessions breaks caching or produces “headers already sent” warnings

Move initialization to an early hook, remove accidental output before headers, and make the affected responses private. If the plugin does not truly need session state, remove session_start() and use WordPress user state, transients or another purpose-built store instead.

Practical decision rule

Use WordPress authentication cookies for login and authorization. Use a custom PHP session only for narrowly defined, temporary server-side workflow data that WordPress cookies are not designed to hold. In both cases, protect the identifier with HTTPS, appropriate cookie attributes, CSRF defenses, capability checks, rotation and server-side invalidation. That division keeps the login path compatible with WordPress while limiting the security and caching complexity introduced by custom state.

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.

Leave a Reply

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

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

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

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.