Before you proceed, make sure you have Redis installed and running on your server. You'll also need to install the PHP Redis extension. If you haven't installed it yet, you can do so using the following command:

sudo apt install php-redis

 

1. Connect to Redis:

$redis = new Redis();
$redis->connect('127.0.0.1', 6379); // Replace with your Redis server IP and port

 

2. Set and Get a key-value pair:

// Setting a key-value pair
$redis->set('my_key', 'Hello, Redis from PHP!');

// Getting the value of a key
$value = $redis->get('my_key');
echo $value; // Output: Hello, Redis from PHP!

 

3. Working with Lists:

// Pushing elements to the end of a list
$redis->rPush('my_list', 'apple');
$redis->rPush('my_list', 'banana');
$redis->rPush('my_list', 'orange');

// Getting the list elements
$list = $redis->lRange('my_list', 0, -1);
print_r($list); // Output: Array ( [0] => apple [1] => banana [2] => orange )

 

4. Working with Sets:

// Adding elements to a set
$redis->sAdd('my_set', 'red');
$redis->sAdd('my_set', 'green');
$redis->sAdd('my_set', 'blue');

// Checking if an element exists in the set
if ($redis->sIsMember('my_set', 'green')) {
echo 'The element "green" exists in the set.';
} else {
echo 'The element "green" does not exist in the set.';
}

 

5. Using Pub/Sub for messaging:

In one PHP script (publisher):

$redisPublisher = new Redis();
$redisPublisher->connect('127.0.0.1', 6379);

// Publish a message to a channel
$redisPublisher->publish('my_channel', 'Hello, subscribers!');

 

In another PHP script (subscriber):

$redisSubscriber = new Redis();
$redisSubscriber->connect('127.0.0.1', 6379);

// Subscribe to a channel
$redisSubscriber->subscribe(['my_channel'], function ($redis, $channel, $message) {
echo "Received message: $message from channel: $channel\n";
});

 

Keep in mind that in a real-world scenario, you might use Redis for caching, queuing, or handling real-time data, among other use cases. The examples provided here are basic to help you understand the PHP Redis integration. For production use, consider handling errors, connection retries, and implementing more advanced features to suit your specific needs.