October DealsAmazon USOctober deal check: compare before you payAmazon 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 NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Set Up Redis as a PHP Session Handler on Ubuntu

A practical Ubuntu guide to moving PHP sessions into Redis, including phpredis installation, SAPI-specific php.ini paths, authentication and prefix parameters, verification with redis-cli monitor, locking caveats, failure testing, and network security.
Length11 min Posted Quest giverVGSources Team

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.

To store PHP sessions in Redis on Ubuntu, install the Redis server and the PHP Redis extension, set session.save_handler = redis and a Redis URL in the php.ini used by your web SAPI, restart PHP-FPM or Apache, and verify the resulting Redis traffic with redis-cli monitor. The exact php.ini path, PHP package availability, authentication syntax, and locking options depend on your Ubuntu and PHP versions, so confirm those details against the phpredis documentation for the extension version you actually installed.

What this setup changes

PHP normally writes sessions according to the session handler selected in php.ini. With the Redis handler, session data is stored as Redis keys instead of local session files. Every web server that can reach the same Redis instance can then read the same session, which is useful when requests for one login are distributed across multiple application servers.

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.

The configuration below uses the phpredis extension. It is not a PHP application-library integration: the handler is selected globally for the PHP SAPI, and the web process must be restarted before its new settings take effect. Redis itself is a separate service, so both the server and the PHP extension must be installed.

  • Server: the Ubuntu package is generally named redis-server.
  • PHP extension: the package used by the tutorials is php-redis.
  • PHP settings: session.save_handler selects Redis and session.save_path supplies the Redis connection URL.
  • Verification: Redis Monitor can show the session-related commands generated when a PHP page starts a session.

Package versions are release-specific. No authoritative package version is established here, and a claim that Ubuntu 24.04 ships a particular Redis 7.x build should not be treated as guaranteed. Check the packages available for your Ubuntu release and the PHP version enabled for your web server.

#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.

Before you begin

Confirm which PHP SAPI serves the site

PHP can have separate configuration trees for the command line, Apache, and PHP-FPM. Editing the CLI configuration while the site runs through FPM will not change web requests. Typical FPM and Apache paths shown in Ubuntu tutorials are:

  • /etc/php/8.3/fpm/php.ini for PHP-FPM.
  • /etc/php/8.3/apache2/php.ini for Apache’s PHP module.

The 8.3 segment is an example, not a universal path. Replace it with the PHP version installed on your machine. If you are unsure, inspect the PHP configuration reported by the SAPI that serves a test page; a command-line check alone only describes the CLI SAPI.

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

Confirm the Redis endpoint you intend to use

The basic local configuration connects to 127.0.0.1 on Redis’s default port, 6379. Redis commonly binds to localhost by default. That is a safe starting point when PHP and Redis run on one host, but it is not a configuration for sharing sessions between machines; a multi-host deployment requires deliberate network binding, authentication, and firewall rules.

Install Redis and phpredis

  1. Refresh the package index if your system has not done so recently: sudo apt update.
  2. Install the server and extension packages used by the Ubuntu tutorials:
    sudo apt install redis-server php-redis
  3. Check that the package names resolve for your Ubuntu release and that php-redis is associated with the PHP version used by the web SAPI. If your distribution uses a versioned extension package or a different PHP repository, use the package that provides the phpredis extension for that SAPI.

Installing the extension does not automatically make it the session handler. The two session directives must still be set in the correct php.ini.

Configure the session handler

Minimal local configuration

Open the php.ini for the SAPI serving the application and set these directives:

session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379"

Keep the value quoted as shown. The first line tells PHP to use phpredis for sessions; the second gives phpredis a TCP endpoint. If the file already contains these directives, edit the active entries rather than leaving conflicting duplicates in place.

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

How the URL is structured

Connection options are appended as a query string to the Redis URL. For example:

session.save_path = "tcp://127.0.0.1:6379?auth=yourpassword&database=1&prefix=myapp_session:"

This example selects database 1, supplies a password, and changes the key prefix. Treat yourpassword as a placeholder for the actual secret; do not publish a real credential in a configuration example, ticket, or log.

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

Several hosts can be listed, separated by commas, when your phpredis build supports that form. A Unix socket is another supported transport; parameters follow the socket path:

session.save_path = "unix:///var/run/redis/redis.sock?persistent=1&weight=1&database=0"

Use a socket only when the Redis socket path and its permissions are correct for the PHP worker account. A TCP URL is usually simpler to troubleshoot and is the form used by the basic Ubuntu setup.

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

Authentication, databases, and key prefixes

Authentication syntax

The documented form shown in the phpredis pull-request examples supplies username and password as an array:

session.save_path = "tcp://127.0.0.1:6379?auth[]=username&auth[]=password"

A single auth=password parameter is also seen in practice. Because parameter parsing has varied between phpredis versions and examples, verify the accepted form in the README that matches your installed extension before relying on it in production. If a password contains characters with URL meaning, percent-encode those characters; this requirement is reported in PHP manual user notes rather than confirmed here against the current manual page.

Selecting a Redis database

Add database=1 (or another approved index) to isolate sessions from unrelated keys. The default database shown in the Unix-socket example is 0. The database number is a Redis logical database, not a separate Redis server; access controls, memory limits, and failure behaviour still apply to the same Redis instance.

Choosing a prefix

Use prefix=myapp_session: to make application keys recognizable and to avoid collisions when several applications share a Redis database. Search-result documentation summaries identify PHPREDIS_SESSION: as the default prefix, while the phpredis examples show that it can be configured. Check the effective default and option spelling for your extension version rather than assuming every release behaves identically.

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

Restart the process that reads php.ini

A running PHP worker does not normally reread php.ini for every request. Restart the SAPI you edited:

  • For PHP-FPM, restart the service for the installed PHP version after editing its FPM configuration.
  • For Apache with the PHP module, restart Apache after editing the Apache PHP configuration.

Use the service name and PHP version present on your Ubuntu installation. Restarting only Redis will not apply a PHP configuration change; restarting only an unrelated PHP version will have no effect on the site.

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)

Verify that PHP is using Redis sessions

Watch Redis commands

Open one terminal and start the Redis monitor:

redis-cli monitor

In another terminal or browser, load a PHP page that calls session_start() and writes a session value. Return to the monitor and look for requests against the session key. One tutorial describes seeing GET and SETEX; search-result text from the phpredis documentation discusses SET with the EX and NX options. Those observations can differ by phpredis and Redis versions, so treat the command names as a version-dependent diagnostic rather than a fixed expected transcript.

Inspect keys by prefix

If you set a custom prefix, you can inspect matching keys with:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
redis-cli keys 'myapp_session:*'

For the reported default prefix, the corresponding pattern is:

redis-cli keys 'PHPREDIS_SESSION:*'

This is a quick check for a small test Redis instance. Avoid using the KEYS command as a routine production diagnostic on a large, busy database because it can scan the keyspace; use an operationally appropriate, incremental inspection method in a production environment.

Interpret an empty monitor

  • If no commands appear, confirm that the browser request reaches the PHP SAPI whose php.ini you edited.
  • Confirm that the phpredis extension is loaded by that SAPI, not only by the CLI.
  • Check the syntax and quoting of session.save_handler and session.save_path, then restart the correct service again.
  • Make sure the test page actually calls session_start(); a page that never starts a session will not create session traffic.

Redis version and command compatibility

A search-result summary attributed to phpredis documentation says the session handler needs Redis support for the EX and NX options of SET, described there as at least Redis 2.6.12. That wording was not confirmed against the complete official README, so use it as a compatibility lead, not as a current guarantee. Check the requirements for the exact phpredis release and Redis package you install.

The distinction matters when diagnosing a monitor trace: a client may use modern SET EX NX semantics while an older tutorial expects SETEX. The trace tells you what your installed combination actually sends; it does not prove that another version will send the same sequence.

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.

Session expiry, locking, and failure behaviour

Expiry and persistence

Redis-backed sessions are Redis keys, so expiry is governed by the TTL that phpredis applies and by the session lifetime configured in PHP. The exact defaults and parameter names should be verified for your PHP and phpredis versions. Redis persistence is a separate concern: sessions survive a Redis restart only when Redis persistence has been configured in redis.conf. The specific persistence directives were not established here, so inspect the configuration and Redis documentation for your release instead of assuming that installing redis-server enables durable session recovery.

Concurrent requests and locking

Two simultaneous requests from one browser can both read and write the same session. The phpredis pull-request material says locking is currently supported only for a single-master Redis setup, including a classic master/replica arrangement with Sentinel. Do not assume that a clustered or multi-master topology provides equivalent session locking.

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

Settings reported in user code include:

  • redis.session.locking_enabled
  • redis.session.lock_expire
  • redis.session.lock_wait_time, reported as microseconds with a default of 2,000
  • redis.session.lock_retries, reported with a default of 10

These names and defaults are low-confidence, user-reported details. Verify that your installed phpredis version supports them and confirm units before enabling or tuning them. A separate issue titled “Failed to lock session” exists, so test concurrent requests in a staging environment rather than assuming that a setting eliminates every race.

When Redis is unavailable

One issue report says a two-second timeout supplied in connection parameters did not end the PHP script promptly when Redis was stopped. A connection timeout is therefore not a guarantee of a fast request failure. Test the failure path with your web server, PHP version, and phpredis build, and set external request, process, and health-check timeouts that prevent a stalled Redis connection from consuming all workers.

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

Secure a production deployment

Keep Redis off public interfaces

For a single-host installation, retaining Redis on localhost limits exposure. If sessions must be shared across hosts, bind Redis only to the private interface or network required by the application, restrict the port with a firewall, and require authentication. Never expose the Redis port directly to the public internet merely because another web server needs session access.

Protect credentials and session data

  • Store the password with the same care as any application secret; session.save_path is configuration data that may be readable by administrators or deployment tooling.
  • Use a dedicated Redis logical database or prefix for the application so operational commands and cleanup jobs cannot accidentally target unrelated keys.
  • Consider the sensitivity of session contents. A stolen Redis credential can expose active sessions, not just cache entries.
  • Test failover and restart behaviour before depending on sessions for a production login flow.

Shared-host and multi-server considerations

Redis provides the shared-storage advantage that local session files cannot provide without a shared filesystem. Every application server must use the same Redis endpoint, authentication, database, prefix, and compatible phpredis behaviour. A typo in any one server’s URL can create apparently random logouts when a load balancer sends a user to that node.

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

Redis sessions compared with other handlers

Consideration Redis handler Local file sessions Database-backed sessions
Sharing across web servers Natural when all servers reach the same Redis instance and use identical settings. Requires a shared filesystem or sticky routing; a server’s local disk is not shared automatically. Shared when every server connects to the same database.
Restart persistence Depends on Redis persistence configuration; installation alone does not establish durable recovery. Depends on the local filesystem and cleanup behaviour. Depends on database durability and the session table implementation.
Expiry and garbage collection Uses Redis key expiry plus PHP session lifetime; verify the effective phpredis parameters. Uses PHP’s file-session cleanup process and filesystem state. Uses the application’s database cleanup strategy and PHP session lifetime.
Concurrent-request locking Locking support and topology limits must be checked for the phpredis version; reported support is for a single-master setup. File locking behaviour is tied to the filesystem and PHP handler. Locking depends on the database driver and transaction design.
Network exposure Requires protecting the Redis port, especially when shared across machines. Can remain local to each web server. Requires protecting the database connection and server.

Redis is most compelling when several PHP workers or hosts need low-latency shared sessions and you can operate Redis securely. It is not automatically the best choice for a single small site: adding a network service introduces another failure mode and another system that must be monitored.

Common mistakes and recovery steps

Editing the wrong php.ini

Symptom: a CLI check shows Redis enabled, but the website still creates file sessions or reports an unavailable handler.

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

Fix: identify whether the site uses FPM or Apache, edit that SAPI’s configuration directory, and restart that service. The example paths with 8.3 are not interchangeable with another installed PHP version.

Leaving the handler set to files

Symptom: Redis Monitor remains quiet while files continue appearing in the PHP session directory.

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.

Fix: ensure the active file contains session.save_handler = redis, not a commented line or a later override that resets it to files.

Malformed query parameters

Symptom: PHP can reach Redis without options but fails after adding a password, database, or prefix.

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

Fix: start with the minimal TCP URL, add one option at a time, URL-encode special password characters, and verify whether your phpredis version expects auth[]=user&auth[]=password or the single-password form.

Assuming a timeout guarantees recovery

Symptom: requests continue waiting after Redis is stopped even though a short timeout was configured.

Fix: reproduce the failure under your exact stack, inspect web-server and PHP worker timeouts, and design an explicit degraded-mode response. Do not validate only the healthy connection path.

Exposing Redis while enabling shared sessions

Symptom: a remote PHP host can connect, but the Redis port is reachable from networks that do not need it.

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

Fix: narrow the bind address and firewall allow-list, require authentication, and keep the endpoint on a private network. Connectivity from one application server is not a reason to permit global access.

Deployment checklist

  • Install redis-server and the phpredis package that matches the web PHP version.
  • Identify the active FPM or Apache php.ini; do not rely on the CLI configuration.
  • Set session.save_handler = redis.
  • Set a quoted tcp:// or approved Unix-socket session.save_path.
  • Add and verify authentication, database, and prefix parameters before using them in production.
  • Restart the correct PHP service.
  • Use redis-cli monitor while loading a page that calls session_start().
  • Check the resulting key prefix in a controlled test environment.
  • Test concurrent requests, Redis restarts, authentication failures, and stopped-Redis behaviour.
  • Restrict Redis binding and firewall access, and decide whether Redis persistence is appropriate for your session policy.
  • Verify phpredis parameter names, defaults, locking support, and Redis version requirements against the documentation for the versions installed on your server.

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 *

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.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver 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.