Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk12 min

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

A practical Ubuntu guide to moving PHP sessions into Redis: install the required packages, edit the correct SAPI php.ini, configure authentication and prefixes, verify traffic, and harden the deployment.
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 phpredis session.save_path in the php.ini used by your web server, restart PHP-FPM or Apache, and verify that requests create Redis session traffic. The exact configuration file depends on your PHP version and SAPI, so changing the CLI configuration alone may have no effect on a website.

What Redis session handling changes

PHP normally stores session data in files on the local machine. With the Redis handler, PHP serializes the session and sends it to a Redis server under a generated key. Each request that calls session_start() reads that key, and a request that changes the session writes it back. Redis can therefore provide one session store for several web servers, provided every server can reach the same Redis instance and uses compatible settings.

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.

Redis is not a replacement for PHP’s session API. Your application still calls session_start(), reads values from $_SESSION, and controls lifetime with PHP session settings. Only the storage handler changes.

Prerequisites and decisions

  • An Ubuntu system with administrative access and a supported PHP installation.
  • A web SAPI to configure: PHP-FPM behind a web server, Apache’s PHP module, or another SAPI.
  • A Redis endpoint reachable from that PHP process. The local default is 127.0.0.1:6379.
  • The php-redis extension installed for the same PHP installation that runs your site.
  • A decision about whether Redis is local to the application or shared by multiple machines. A shared deployment requires network controls and usually authentication.

Package names and available PHP versions vary by Ubuntu release. The commands below use the package names reported by common Ubuntu tutorials; confirm that redis-server and php-redis resolve for your release and PHP version before applying them.

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

Install Redis and the PHP extension

  1. Refresh package metadata:

    sudo apt update
  2. Install the server and extension:

    sudo apt install redis-server php-redis

    If your host has multiple PHP versions, check that the extension is enabled for the version used by your site. A CLI check such as php -m | grep -i redis only describes the CLI SAPI; it does not prove that PHP-FPM or Apache loaded the extension.

  3. Confirm that Redis is running:

    sudo systemctl status redis-server
    redis-cli ping

    A healthy local server normally answers PONG. If the service is stopped, start it with sudo systemctl start redis-server and enable it at boot with sudo systemctl enable redis-server, subject to your operating policy.

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

Find the php.ini that your website actually uses

Ubuntu keeps separate configuration trees for different PHP versions and SAPIs. Typical paths include:

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

The 8.3 directory is an example, not a requirement. Replace it with the version installed on your machine. To identify the CLI version and loaded file, run:

php --version
php --ini

For a web request, create a temporary page containing <?php phpinfo();, open it through the same virtual host as your application, and read the “Loaded Configuration File” value. Remove that page immediately after checking it because phpinfo() exposes environment details.

Do not assume that editing the CLI file changes PHP-FPM. A frequent failure pattern is a successful php -m check followed by a website that still reports file-based sessions because the FPM pool loaded a different configuration tree.

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

Set the basic Redis session handler

Open the php.ini identified for the web SAPI and set these directives:

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

Keep the value in quotes. The tcp:// scheme tells phpredis to connect over TCP to the local Redis listener. If Redis runs on another host, replace the address with that host’s private address or DNS name and apply firewall rules before exposing the service.

Leave unrelated session directives unchanged until the basic connection works. PHP’s session lifetime, cookie attributes, garbage-collection settings, and application-level logout logic remain separate from the Redis connection string.

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.

Add authentication, a database, or a key prefix

phpredis accepts connection parameters in a query string appended to session.save_path. A representative form is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
session.save_path = "tcp://127.0.0.1:6379?auth=yourpassword&database=1&prefix=myapp_session:"

The parameters shown in phpredis examples include authentication, a Redis logical database number, and a key prefix. Parameter spelling and authentication syntax can differ between extension versions, so check the README for the phpredis version installed on your server before relying on a production setting.

Option Example Purpose and cautions
Host and port tcp://127.0.0.1:6379 Defines the Redis endpoint. Use a private address for a remote server and restrict access with a firewall.
Password auth=yourpassword A single-value form appears in working configurations. Verify the accepted form for your phpredis release.
Username and password auth[]=user&auth[]=password The array form is shown in phpredis connection examples for ACL credentials. Confirm support in your installed release.
Logical database database=1 Stores sessions in Redis database 1 instead of the default database 0. It is a namespace, not a security boundary.
Prefix prefix=myapp_session: Adds an application-specific prefix so keys are easy to identify and less likely to collide with other data.
Persistent connection persistent=1 Can be used in connection strings supported by phpredis. Test connection reuse with your PHP-FPM worker model before enabling it broadly.
Weight weight=1 Relevant when using multiple listed hosts; it has no useful effect for one endpoint.

Passwords containing characters such as &, ?, or spaces must be percent-encoded so they are not interpreted as query-string separators. Store the resulting value with permissions that prevent ordinary users from reading it.

Unix-socket alternative

When Redis and PHP share a machine, phpredis can use a Unix socket instead of TCP. An example documented in phpredis material is:

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

The socket path and permissions must match your distribution. The PHP-FPM or Apache user needs permission to open the socket; otherwise the handler will fail even though redis-cli works for an administrator.

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

Multiple Redis hosts

phpredis supports listing multiple hosts separated by commas in the save path. This is not automatically equivalent to a fully coordinated Redis cluster. The documented locking behavior is limited to a single-master setup, such as a traditional master/replica arrangement managed with Sentinel. Treat multi-host session routing as a topology decision: verify how your phpredis release selects a host, handles failover, and maintains session consistency before using it for authentication sessions.

Restart the SAPI that serves the application

Configuration changes are read when PHP workers start. Restart the service that owns the web requests:

sudo systemctl restart php8.3-fpm

Replace 8.3 with your installed FPM version. For Apache’s PHP module, restart Apache instead:

sudo systemctl restart apache2

If a reverse proxy forwards requests to a separate PHP-FPM host, restart FPM on that host, not only the proxy. A graceful reload may be preferable on a busy site, but use the service procedure appropriate to your deployment and confirm that new workers loaded the changed file.

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

Verify that PHP is writing sessions to Redis

Use an observable test rather than assuming that a restarted service applied the setting.

  1. In one terminal, start the Redis monitor:

    redis-cli monitor

    This prints commands received by the selected Redis server. Keep the terminal restricted because monitor output can reveal session-related data and command arguments.

  2. Create a temporary PHP page in the same virtual host:

    <?php
    session_start();
    $_SESSION['redis_probe'] = date('c');
    echo 'Session ID: ' . session_id();
  3. Load the page twice in the same browser. The monitor should show session reads and writes. Depending on your phpredis and Redis versions, you may see commands based on SETEX or on SET with expiration and conditional options such as EX and NX. Do not treat one command name from a tutorial as universal; observe your installed versions.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  4. Optionally inspect keys using the configured prefix:

    redis-cli keys 'PHPREDIS_SESSION:*'
    redis-cli keys 'myapp_session:*'

    The commonly reported default prefix is PHPREDIS_SESSION:, but an explicit prefix is safer when Redis is shared. Avoid running the KEYS command on a large production database because it can block while scanning every key; use a controlled test database or an incremental scan procedure instead.

  5. Delete the test page and stop monitoring when finished.

If no Redis traffic appears, inspect the web SAPI’s phpinfo() output, confirm that the Redis extension is loaded there, and verify that the edited session.save_path is the active value.

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

Session expiration, restarts, and persistence

Redis-backed sessions still expire according to the TTL PHP supplies through the session handler and your PHP session settings. Redis key expiration is not the same as PHP’s file-session garbage collection; do not infer one system’s behavior from the other. Test an actual login, idle timeout, and logout flow with your application’s configured lifetime.

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.

Redis data does not necessarily survive a Redis restart. Sessions survive a restart only when Redis persistence is configured in redis.conf and the resulting recovery meets your availability requirements. The appropriate persistence mode and directives depend on your Ubuntu and Redis deployment, so inspect the active configuration and test a controlled restart rather than assuming that every installation preserves session keys.

Many applications intentionally accept losing sessions during a Redis outage and force users to sign in again. Others require session continuity and plan backups, replication, and recovery. Decide this behavior explicitly; Redis persistence cannot compensate for an untested failover plan.

Concurrent requests and session locking

Two simultaneous requests from one browser can both open the same session. Without effective locking, each request may read an older copy and the last write can overwrite the other request’s changes. This is especially visible with parallel AJAX calls that update different session fields.

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

phpredis includes session-locking support in single-master configurations. Settings reported for builds that expose the feature include:

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

These names and defaults should be checked against the README and phpinfo() output for your installed extension before use. Enable and tune locking only after measuring request patterns; a very short lock expiration can permit overlapping writers, while a long wait can increase latency.

Test failure behavior as well. An issue report describes a case where a two-second connection timeout in the parameters did not end a script promptly when Redis was stopped. Your application should have an explicit outage policy, such as returning a controlled error, bypassing nonessential session writes, or directing traffic to a healthy node. Do not assume that a timeout value guarantees an upper bound on total request time.

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

Secure a Redis session store

  • Redis commonly binds to localhost by default. Keep that arrangement when PHP and Redis are on the same host.
  • If several application servers share Redis, bind Redis only to the required private interfaces and firewall port 6379 so it is not reachable from the public internet.
  • Configure authentication appropriate to your Redis version, and use ACL credentials when supported. Put credentials in protected configuration files rather than source control.
  • Use a dedicated logical database or prefix for sessions, but remember that logical databases and prefixes do not isolate an attacker who can authenticate to Redis.
  • Restrict access to redis-cli monitor, key inspection, and administrative commands because session identifiers and values may be sensitive.
  • Use TLS or a private encrypted network when traffic crosses untrusted networks, if your Redis and phpredis versions support the required TLS configuration.
  • Rotate credentials and invalidate sessions after a suspected credential exposure.

Common failures and fixes

“Class Redis” or extension-not-found errors

The php-redis package may be installed for one PHP version while the website runs another. Check the web SAPI’s phpinfo() page, install the matching extension package, and restart the correct service.

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

The site still creates files in /var/lib/php/sessions

You probably edited the CLI php.ini, an inactive version directory, or a pool-specific override. Confirm the loaded configuration through the website, search for duplicate session.save_handler and session.save_path directives, then restart PHP-FPM or Apache.

“Connection refused” or timeout errors

Check systemctl status redis-server, run redis-cli ping from the PHP host, and verify the host and port in the save path. For a remote endpoint, inspect firewall rules and Redis bind settings. A successful connection from an administrator’s shell does not prove that the web worker can reach the same address.

Authentication failures

Verify the password or ACL username, percent-encode reserved characters, and confirm the parameter syntax supported by your phpredis release. Test with the same credentials using a Redis client before restarting PHP again.

Sessions disappear after a restart

Check whether Redis persistence is enabled and whether the restart was a planned service restart, a host reboot, or a failover. If losing sessions is unacceptable, test persistence and recovery and document the expected behavior.

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

Users are logged out intermittently behind a load balancer

Confirm that every PHP server points to the same Redis endpoint, database, and prefix. Check clock-independent session expiry settings and inspect monitor output on the shared Redis instance. A per-host Redis server causes each load-balanced request to see a different session store.

Requests hang when Redis is unavailable

Do not rely solely on a nominal connection timeout. Reproduce the outage in staging, measure total request time, and configure application and web-server limits that fail predictably. Review lock wait and retry settings for your extension version.

Redis versus file and database sessions

Consideration Redis sessions File sessions Database sessions
Shared storage across web servers Yes, when all servers reach the same Redis instance and use identical settings. Not by default; requires shared storage or sticky routing. Yes, when every server uses the same database and table design.
Persistence across restarts Depends on Redis persistence and recovery configuration. Depends on the local filesystem and cleanup behavior. Usually tied to database durability and backup policy.
Expiry behavior Redis key TTLs plus PHP session settings. PHP session settings plus file garbage collection. Application or database cleanup plus PHP session settings.
Concurrent requests Requires correctly configured phpredis locking and a supported topology. Depends on the file handler’s locking behavior. Depends on transaction and locking design.
Network exposure Requires securing the Redis listener, especially for remote access. No session network port when stored locally. Requires securing the database connection.

Redis is a strong fit when several PHP workers or servers need low-latency shared sessions and you can operate Redis securely. Local files remain simpler for a single server. A database may be preferable when operational standards already require database durability and auditing, although it adds database query and contention considerations.

Production checklist

  • Install redis-server and the php-redis extension matching the web PHP version.
  • Verify the active FPM or Apache php.ini, not only the CLI configuration.
  • Set session.save_handler = redis and a tested tcp:// or Unix-socket save path.
  • Choose an explicit prefix and, when appropriate, a dedicated Redis logical database.
  • Confirm authentication syntax and percent-encode reserved password characters.
  • Restart the SAPI and verify with redis-cli monitor and a temporary session page.
  • Test expiration, concurrent requests, Redis restarts, failover, and an unavailable-Redis scenario.
  • Keep Redis off public interfaces, restrict port 6379, and protect credentials and diagnostic commands.
  • Document whether sessions are allowed to disappear during an outage and how users recover.

Frequently Asked Questions

Do I need to change my PHP application code?

Usually no. Existing code that calls session_start() continues to use $_SESSION; the storage change is made in PHP configuration. Test application-specific serialization and logout behavior after switching handlers.

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

Why does changing /etc/php/8.3/cli/php.ini not change my website?

The website normally uses PHP-FPM or Apache, each with its own configuration path. Find the loaded file through the web SAPI’s phpinfo() output, edit that file, and restart the corresponding service.

Can I use Redis on another server?

Yes, but set the save path to the reachable private address, secure authentication, restrict firewall access, and verify latency and failure behavior. Never expose an unauthenticated Redis listener to the public internet.

What happens to sessions if Redis stops?

Requests may fail, wait, or lose session access depending on connection, retry, and locking behavior. Test an outage with your exact phpredis version; a nominal timeout does not guarantee that the entire PHP request ends within that interval.

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 *

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
PC Slower Than It Used to Be?Free scan - under a minute
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.