Learn how to store and retrieve data in Redis using PHP. Work with strings, lists, and hashes to optimize data handling and caching.
Introduction
Redis is an in-memory key-value store used for caching, session management, and real-time applications. Unlike traditional databases, Redis supports multiple data structures, making it a powerful tool for storing and retrieving data efficiently.
Redis provides:
- Strings – Simple key-value pairs, ideal for caching and counters.
- Lists – Ordered collections, useful for messaging and queues.
- Hashes – Key-value storage within a key, great for storing objects.
This guide covers:
- Using Redis Strings, Lists, and Hashes in PHP
- Storing and retrieving data with PHPRedis and Predis
- Practical use cases and best practices
1. Setting Up Redis in PHP
Using PHPRedis (C Extension)
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
Using Predis (Pure PHP Client)
require 'vendor/autoload.php';
$redis = new Predis\Client();
Once connected, you can start working with different Redis data types.
2. Storing and Retrieving Strings in Redis
Storing a String Value
$redis->set("user:1001", "John Doe");
Retrieving a String Value
echo $redis->get("user:1001"); // Output: John Doe
Setting Expiration for a Key
$redis->setex("session:12345", 300, "User Data"); // Expires in 300 seconds
Incrementing and Decrementing Numeric Values
$redis->set("counter", 10);
$redis->incr("counter"); // Increments by 1 (counter = 11)
$redis->decr("counter"); // Decrements by 1 (counter = 10)
Use Cases for Strings
✅ Caching user authentication tokens
✅ Storing configuration settings
✅ Maintaining counters (e.g., post views, likes)
3. Working with Redis Lists in PHP
Lists are ordered collections of values, allowing push, pop, and range operations.
Adding Elements to a List
$redis->rpush("queue:messages", "Message 1");
$redis->rpush("queue:messages", "Message 2");
$redis->lpush("queue:messages", "Message 0"); // Pushes to the front
Retrieving Elements from a List
print_r($redis->lrange("queue:messages", 0, -1));
// Output: Array ( [0] => Message 0 [1] => Message 1 [2] => Message 2 )
Popping Elements from a List
$firstMessage = $redis->lpop("queue:messages"); // Removes from the front
$lastMessage = $redis->rpop("queue:messages"); // Removes from the end
Getting the Length of a List
echo $redis->llen("queue:messages"); // Number of elements
Use Cases for Lists
✅ Implementing queues for job processing
✅ Storing chat messages in order
✅ Managing task lists
4. Using Redis Hashes to Store Objects
Hashes allow storing multiple fields under one key, making them ideal for user profiles, product details, and metadata storage.
Storing Data in a Hash
$redis->hset("user:1001", "name", "John Doe");
$redis->hset("user:1001", "email", "john@example.com");
$redis->hset("user:1001", "age", 30);
Retrieving a Specific Field
echo $redis->hget("user:1001", "email"); // Output: john@example.com
Retrieving All Fields in a Hash
print_r($redis->hgetall("user:1001"));
Output
Array ( [name] => John Doe [email] => john@example.com [age] => 30 )
Checking If a Field Exists
if ($redis->hexists("user:1001", "email")) {
echo "Email exists!";
}
Deleting a Field from a Hash
$redis->hdel("user:1001", "age");
Use Cases for Hashes
✅ Storing user profiles efficiently
✅ Caching structured data (e.g., product details)
✅ Managing API session data
5. Performance Considerations for Redis Storage
1. Use Key Expiry for Temporary Data
$redis->expire("user:1001", 3600); // Expires in 1 hour
2. Optimize Large Lists with Trim
$redis->ltrim("queue:messages", 0, 99); // Keep only the last 100 messages
3. Avoid Large Hashes for Scalability
Instead of a single large hash, break data into multiple smaller hashes.
6. Best Practices for PHP Redis Data Storage
✅ Use strings for simple key-value storage and counters.
✅ Use lists for ordered data like message queues.
✅ Use hashes for structured data storage.
✅ Set expiration times for temporary data to prevent memory issues.
✅ Monitor Redis memory usage using INFO memory
.
Conclusion
Redis provides a fast and flexible way to store structured data in PHP applications. Using strings, lists, and hashes, developers can optimize caching, queue processing, and structured data storage.
This guide covered:
- Storing and retrieving Redis strings in PHP
- Using lists for queue-like data storage
- Managing structured objects with Redis hashes
- Best practices for Redis data management
By following these techniques, you can improve application performance while leveraging Redis effectively.