Skip to main content
Redis Basics
CHAPTER 15 Intermediate

Connect PHP to Redis | Predis and PhpRedis Tutorial

Updated: May 16, 2026
15 min read

# CHAPTER 15

Redis with PHP Applications

1. Introduction

Typing commands into the redis-cli terminal is fantastic for learning, but it is not how real software works. In a production environment, the user interacts with an HTML website, the website talks to your backend code, and the backend code talks to Redis. In this chapter, we will bridge the gap between the PHP programming language and the Redis memory engine, allowing us to build blazing-fast dynamic websites.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the difference between PhpRedis and Predis.
  • Connect to the Redis server via PHP.
  • Execute basic SET and GET commands programmatically.
  • Serialize complex PHP arrays to JSON for Redis storage.
  • Architect a basic Database Query Caching layer.

3. The Two PHP Clients

PHP cannot speak to Redis natively. It requires a client library.
  1. 1. PhpRedis: A compiled C-extension. It is incredibly fast but requires you to modify your server's core PHP installation.
  1. 2. Predis: A pure PHP library installed via Composer. It is slightly slower, but incredibly easy to install and heavily favored by modern frameworks like Laravel.

*For this tutorial, we will use the syntax of PhpRedis (the official Redis class).*

4. Establishing the Connection

Create a file named redis_connect.php.
php
12345678910111213141516
<?php
// 1. Instantiate the Redis Object
$redis = new Redis();

// 2. Connect to the local server on the default port
try {
    $redis->connect(&#039;127.0.0.1', 6379);
    
    // If you set a password in Chapter 14, authenticate here:
    // $redis->auth('zx92!PqR5$mK8#vL1@bN4%cX7^hJ0&wY3*');
    
    echo "Successfully connected to Redis!<br>";
} catch (Exception $e) {
    die("Could not connect to Redis: " . $e->getMessage());
}
?>

5. Executing Basic Commands

Once connected, every CLI command you learned simply becomes a PHP method!
php
123456789101112131415
<?php
// SET a string
$redis->set("company_name", "TechCorp Inc.");

// GET a string
$name = $redis->get("company_name");
echo $name; // Outputs: TechCorp Inc.

// Execute an Atomic INCR
$redis->incr("page_views");
echo "Views: " . $redis->get("page_views");

// Set with Expiration (SETEX)
$redis->setex("temporary_code", 300, "9999");
?>

6. Serializing PHP Arrays

Redis cannot store a native PHP Array or Object directly. You must mathematically flatten it into a String first. The industry standard is json_encode.
php
12345678910111213141516171819
<?php
$user_profile = [
    "name" => "Alice",
    "email" => "alice@example.com",
    "role" => "Admin"
];

// Flatten the array to a JSON string
$json_string = json_encode($user_profile);

// Store it in Redis
$redis->set("user:101", $json_string);

// Retrieve and Decode it back to an Array
$stored_string = $redis->get("user:101");
$retrieved_array = json_decode($stored_string, true);

echo $retrieved_array[&#039;email']; // Outputs: alice@example.com
?>

7. Mini Project: The Query Caching Layer

This is the most important code snippet you will ever write. We will combine MySQL and Redis. Goal: If the data is in Redis, serve it instantly. If not, fetch it from MySQL, save it to Redis, and then serve it.
php
12345678910111213141516171819202122232425
<?php
$product_id = 55;
$cache_key = "product_data:" . $product_id;

// 1. Try to fetch from Redis
$cached_data = $redis->get($cache_key);

if ($cached_data) {
    echo "Served blazing fast from Redis Cache!<br>";
    $product = json_decode($cached_data, true);
} else {
    echo "Cache Miss! Fetching from slow MySQL database...<br>";
    
    // 2. Simulate a slow MySQL Query
    // $db_result = mysqli_query($conn, "SELECT * FROM products WHERE id=55");
    $db_result = ["id" => 55, "name" => "Laptop", "price" => 1200]; 
    
    // 3. Save the result into Redis for 10 minutes (600 seconds)
    $redis->setex($cache_key, 600, json_encode($db_result));
    
    $product = $db_result;
}

echo "Displaying Product: " . $product[&#039;name'];
?>

8. PHP Session Storage in Redis

By default, PHP stores $_SESSION data in temporary text files on the server's hard drive. If you have 2 web servers, Server A cannot read the text files on Server B! You can configure your php.ini file to bypass the hard drive and store all sessions in the centralized Redis RAM engine automatically!
ini
12
session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379"

Now, sessionstart() executes perfectly at the speed of light across your entire cluster of servers.

9. Common Mistakes

  • Forgetting to serialize data: A beginner tries to run $redis->set("myarray", [1, 2, 3]);. PHP will throw a severe warning, and the data will not be saved properly. Redis requires strictly Strings, Hashes, Sets, etc. You must run jsonencode on complex variables before using the SET command.

10. Best Practices

  • Graceful Degradation: What if the Redis server crashes? If your PHP code throws a Fatal Error and dies, your entire website goes offline. You must wrap your Redis connection code in a try/catch block. If Redis is dead, the catch block should silently bypass the cache and force the application to fall back to the slow MySQL database. The website will be slow, but it will still be online!

11. Exercises

  1. 1. What native PHP function must you use to flatten an associative array before passing it to the $redis->set() method?
  1. 2. What specific configuration file must you edit to force PHP to handle global $SESSION data using the Redis engine rather than local hard drive files?

12. Redis Challenges

You are implementing a caching layer. You run $cacheddata = $redis->get("weathernyc");. The result returned to the $cacheddata variable is false. What specific architectural scenario does this boolean value represent, and what algorithmic logic must your PHP script execute next? *(Answer: The false return value represents a "Cache Miss"—the data was either never created or its TTL expired and it was deleted. Your PHP script must immediately execute a fallback query to the primary database or external API, fetch the fresh data, display it to the user, and then execute $redis->setex() to repopulate the Redis cache for subsequent users).*

13. MCQ Quiz with Answers

Question 1

When architecting the primary "Cache-Aside" pattern in a PHP/MySQL environment, what is the mandatory logical sequence executed by the backend application upon receiving a user request?

Question 2

What is the fundamental architectural advantage of modifying the php.ini file to configure the session.savehandler = redis directive across a fleet of load-balanced web servers?

14. Interview Questions

  • Q: Write a conceptual PHP script utilizing a try/catch block that connects to Redis, attempts to fetch a cached string, and gracefully degrades to a simulated SQL query fallback if the Redis connection times out.
  • Q: Explain the mechanical differences between the PhpRedis C-extension and the Predis package. Why might a DevOps engineer working in a highly restricted containerized environment prefer Predis?

15. FAQs

Q: Do I need to use $redis->close() at the end of my PHP script? A: You don't have to. PHP automatically closes the TCP connection to Redis the millisecond the script finishes generating the HTML page. However, using persistent connections (pconnect) is a more advanced topic for massive scale!

16. Summary

You are now an Application Developer. By translating the CLI commands into object-oriented PHP methods, handling JSON serialization, and architecting the fundamental "Cache Miss" fallback logic, you have successfully integrated a high-performance memory engine into your web stack.

17. Next Chapter Recommendation

PHP handles requests synchronously, blocking the thread until it finishes. But what if we are working with an asynchronous runtime like Node.js, capable of keeping thousands of WebSockets open simultaneously? In Chapter 16: Redis with Node.js Applications, we will integrate Redis with JavaScript.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·