tencent cloud

PHP Connection Sample
Last updated: 2025-08-19 14:58:48
PHP Connection Sample
Last updated: 2025-08-19 14:58:48

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"; // Redis instance private IP
$port = 6379; // Redis 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.

Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback