tencent cloud

Tencent Cloud Distributed Cache (Redis OSS-Compatible)

PHP Connection Sample

PDF
Focus Mode
Font Size
Last updated: 2026-03-18 15:26:45

Prerequisites

Download the client phpredis.
Note:
Note: If you use TencentOS, you can install phpredis with the command yum install php-pecl-redis.

Example Code

<?php
/**
* Tencent Cloud Redis Connection and Operation Example
* Documentation: https://github.com/phpredis/phpredis
*/
// Redis connection configuration
$host = "192.xx.xx.26"; // Distributed Cache instance private IP
$port = 6379; // Distributed Cache port
$instanceid = "crs-xxxxxxxx"; // Instance ID
$pwd = "your password"; // Instance password

// Create Redis client instance
$redis = new Redis();

// 1. Connect to Redis server
if (!$redis->connect($host, $port)) {
die("Connection failed: " . $redis->getLastError());
}

// 2. Authentication (Tencent Cloud format: instanceid:password)
$authString = $instanceid . ":" . $pwd;
if (!$redis->auth($authString)) {
die("Authentication failed: " . $redis->getLastError());
}

// 3. Key-value operation example
$key = "redis";
$value = "tencent";

// Set key-value pair
if (!$redis->set($key, $value)) {
die("Set key failed: " . $redis->getLastError());
}
echo "Successfully set key: $key, value: $value\\n";

// Get value by key
$result = $redis->get($key);
if ($result === false) {
die("Get key failed: " . $redis->getLastError());
}
echo "Retrieved key: $key, value: " . $result . "\\n";

// 4. Close connection when done (optional)
$redis->close();
?>

Execution Result

Note:
Note: If an exception occurs during connection, please refer to Private Network Unable to Connect Location Guide to fix it.


Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback