Tutorial
PHP and Redis
February 26, 20262 minute read
TL;DR:Install the PhpRedis extension via PECL (pecl install redis), create aRedisinstance, callconnect()with your host and port, then use methods likeset(),get(), anddel()to read and write data.
Redis is a high-performance, in-memory data store used for caching, session management, and real-time analytics. The PhpRedis extension gives your PHP applications direct access to Redis with minimal overhead.
#What you'll learn
- How to install the PhpRedis extension with PECL
- How to connect a PHP application to a Redis server
- How to perform basic CRUD operations (set, get, delete)
- How to add Redis caching to your PHP application
#Prerequisites
- PHP 7.4 or later (PHP 8.x recommended)
- PECL (included with most PHP installations; install
pkg-php-toolson Debian/Ubuntu if needed) - A running Redis server (see the quick start guide)
#How do I install PhpRedis?
PhpRedis is a C-based PHP extension installed through PECL. If you don't have PECL available, install it first:
Then install the PhpRedis extension:
After installation, make sure the extension is enabled in your
php.ini:Restart your web server or PHP-FPM for the change to take effect.
#How do I connect to Redis from PHP?
Create a new
Redis instance and call connect() with your Redis server's hostname and port:Replace
hostname, port, and password with the values for your Redis instance, then save the file as connect.php.Run the script:
You should see
PONG printed to the terminal. You can verify the connection on the server side with the MONITOR command:#How do I perform CRUD operations with PhpRedis?
Once connected, use the built-in methods on the
Redis object to store and retrieve data:PhpRedis also supports hashes, lists, sets, sorted sets, and streams. See the PhpRedis documentation for the full API.
#How do I add Redis caching to a PHP application?
A common pattern is to check Redis for cached data before querying a slower data source:
You can also use Redis as a PHP session handler by adding the following to
php.ini:#What about Predis vs PhpRedis?
Predis is a pure-PHP Redis client that requires no compiled extension. PhpRedis is a C extension and is generally faster. Choose Predis if you cannot install C extensions in your environment; choose PhpRedis for best performance. Both support Redis Cluster and Sentinel.
#Next steps
- PhpRedis GitHub repository -- full API reference and examples
- Redis Cluster support for PhpRedis
- Redis Sentinel support for PhpRedis
- Predis GitHub repository -- pure-PHP alternative
- Redis distributed locks in PHP
- Getting Started with Redis & PHP
