keepcalculator

06 Numbers and Powers

Store PHP Sessions in Memcached with Nginx on Debian

Card No. 06·80344 · Updated · Standard formula, shown below

This guide walks you through configuring PHP to store session data in Memcached while running Nginx on Debian. By offloading sessions from disk to memory, you get faster session reads/writes and a central store that can be shared across multiple web servers. You’ll need a Debian server with Nginx and PHP already installed, plus root or sudo access.

What You’ll Need

  • A Debian server (10, 11, or 12) with Nginx installed and running.
  • PHP-FPM installed and configured to work with Nginx (e.g., via php-fpm).
  • Root or sudo access to install packages and edit configuration files.
  • Basic familiarity with the command line and editing files in a terminal.

Step-by-Step

  1. Install Memcached and the PHP extension
    Run the following commands to install Memcached and the PHP Memcached extension (which is more feature-rich than the older memcache extension):

    sudo apt update
    sudo apt install memcached php-memcached

    This installs the Memcached server and the PHP extension. The extension will be enabled automatically.

  2. Verify Memcached is running
    Check the service status and confirm it’s listening on the default port (11211):

    sudo systemctl status memcached
    ss -tulpn | grep 11211

    If it’s not running, start it with sudo systemctl start memcached and enable it to start on boot with sudo systemctl enable memcached.

  3. Find your PHP-FPM configuration
    The PHP configuration file is usually at /etc/php/<version>/fpm/php.ini (e.g., /etc/php/8.2/fpm/php.ini). Find your version with php -v.
  4. Edit php.ini to use Memcached for sessions
    Open the file with sudo:

    sudo nano /etc/php/<version>/fpm/php.ini

    Locate the session.save_handler and session.save_path lines. Change them to:

    session.save_handler = memcached
    session.save_path = "127.0.0.1:11211"

    If you have multiple Memcached servers, you can list them comma-separated, e.g., "server1:11211,server2:11211".

  5. Restart PHP-FPM
    After saving the changes, restart PHP-FPM to apply them:

    sudo systemctl restart php-<version>-fpm

    Replace <version> with your PHP version (e.g., php8.2-fpm).

  6. Test that sessions are stored in Memcached
    Create a simple PHP test file in your web root (e.g., /var/www/html/test.php) with the following content:

    <?php
    session_start();
    $_SESSION['test'] = 'hello';
    echo session_id();
    ?>

    Access it via your browser (e.g., http://your-server/test.php). Then, from the command line, check Memcached for the session key:

    echo 'stats items' | nc 127.0.0.1 11211

    You should see an item count that increases. To see the actual key, use stats cachedump <slab> <limit> (you may need to install libmemcached-tools for easier debugging).

  7. Optional: Tune Memcached for session storage
    Edit /etc/memcached.conf to adjust memory (default 64MB) and other settings. For example, to set 256MB:

    -m 256

    Restart Memcached after changes: sudo systemctl restart memcached.

Common Mistakes

  • Using the wrong PHP extension – The php-memcache (without ‘d’) uses a different save_handler (memcache). Make sure you installed php-memcached and use session.save_handler = memcached.
  • Forgetting to restart PHP-FPM – Changes to php.ini only take effect after restarting PHP-FPM.
  • Memcached not running – If the service is down, PHP will fail to write sessions, causing errors or blank pages.
  • Firewall blocking port 11211 – If Memcached is on a different server, ensure the port is open and accessible.
  • Session path syntax – For memcached, the path is a comma-separated list of host:port without any extra characters.

Tips

  • Use a Unix socket for local connections – For better performance, configure Memcached to listen on a Unix socket (e.g., -s /tmp/memcached.sock) and set session.save_path to unix:///tmp/memcached.sock.
  • Set a reasonable session lifetime – Memcached evicts data when memory is full, so set session.gc_maxlifetime to a value that matches your needs (e.g., 1440 seconds).
  • Monitor Memcached usage – Use memcached-tool (from libmemcached-tools) or echo stats | nc to check hit rates and memory usage.
  • Consider sticky sessions if using multiple web servers – If you have a load balancer, you can either share Memcached instances or use sticky sessions to avoid cross-server session issues.

Troubleshooting

If sessions are not working, follow these steps:

  1. Check PHP error logs – Look at /var/log/php8.x-fpm.log or the Nginx error log for messages about session save handler failures.
  2. Verify Memcached is accessible – Run telnet 127.0.0.1 11211 and type stats. If you get a connection refused, Memcached isn’t running.
  3. Confirm the extension is loaded – Run php -m | grep memcached to ensure the extension is active.
  4. Check php.ini values – Run php -i | grep session.save to see the effective settings. If they don’t match your edits, you may have edited the wrong php.ini (e.g., CLI vs FPM).
  5. Test with a simple script – Create a script that writes a session and then reads it back; if it fails, the issue is likely configuration.
  6. Ensure permissions are correct – If using a Unix socket, make sure the PHP-FPM user (usually www-data) has read/write access to the socket file.

Frequently Asked Questions

What is the difference between memcache and memcached extensions?

The memcache extension is older and less feature-rich. memcached is a newer, more maintained extension with better performance and support for binary protocol, SASL authentication, and more.

Can I use Memcached for sessions across multiple servers?

Yes, that’s a common use case. Point all servers to the same Memcached server (or cluster) in session.save_path. However, ensure low latency between servers and consider using a dedicated Memcached cluster for reliability.

How do I set session lifetime with Memcached?

Set session.gc_maxlifetime in php.ini (default 1440 seconds). Memcached will expire keys based on that value, but note that Memcached also evicts data when memory is full, so ensure enough memory is allocated.

What happens if Memcached goes down?

PHP will fail to read/write sessions, causing errors or redirect loops. For high availability, use a Memcached cluster or have a fallback session handler (e.g., files) as a backup.

Is it safe to store sessions in Memcached?

Yes, but keep in mind that Memcached has no built-in authentication or encryption. If your Memcached server is exposed to untrusted networks, secure it with a firewall or use SASL authentication.

Can I use both file and Memcached sessions?

Not simultaneously. PHP uses one save handler at a time. You can switch between them, but you cannot have both active for the same PHP process.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →