search
HomeBackend DevelopmentPHP TutorialAn Introduction to Redis in PHP using Predis

An Introduction to Redis in PHP using Predis

Core points

  • Redis is a popular open source data structure server that features far more than simple key-value storage thanks to its built-in data types. It is widely used by large companies and can be used as a session handler or to create online chat or live booking systems.
  • Redis and Memcache perform similarly in terms of basic operations, but Redis provides more features such as memory and disk persistence, atomic commands and transactions, and server-side data structures.
  • Predis is a flexible and fully functional PHP Redis client library that allows PHP developers to interact with Redis using PHP code. It supports a variety of Redis features, including transactions, pipelines, and clusters.
  • Redis commands include SET, GET, EXISTS (for storing and checking temporary information), INCR and DECR (for maintaining counters), HSET, HGET, HINCRBY and HDEL (for processing hash data types), and EXPIRE, EXPIREAT, TTL, and PERSIST (for processing data persistence).

Redis is an open source data structure server with a memory data set that functions far more than simple key-value storage due to its built-in data types. It was launched in 2009 by Salvatore Sanfilippo and has grown rapidly due to its popularity. It was selected by VMware (later hired Sanfilippo to participate in the project full time), GitHub, Craigslist, Disqus, Digg, Blizzard, Instagram and other large companies (see redis.io/topics/whos-using-redis). You can use Redis as a session handler, which is especially useful if you use a multi-server architecture behind a load balancer. Redis also has a publish/subscribe system, which is ideal for creating online chat or live subscription systems. For documentation and more information about Redis and all its commands, visit the project's website redis.io. There is a lot of debate about which Redis or Memcache is better, but as the benchmarks show, they perform almost the same in terms of basic operations. Redis has more features than Memcache, such as memory and disk persistence, atomic commands and transactions, and instead of logging every change to disk, use server-side data structures instead. In this article, we will use the Predis library to learn about some of the basic but powerful commands that Redis provides.

Easy to install

Redis is easy to install, and brief installation instructions are posted on the product's download page. In my experience, if you are running Ubuntu, you will get an error if you don't have TCL installed (just run sudo apt-get install tcl). After installing Redis, you can run the server:

gafitescu@ubun2:~$ /usr/local/bin/redis-server
* The server is now ready to accept connections on port 6379

Redis client libraries are available in many languages, which are listed on the Redis website, and each language is usually available in multiple languages! For PHP, there are five. In this article, I'm going to use the Predis library, but you might also want to know about phpredis, which is compiled and installed as a PHP module. If you installed Git on your machine like I did, you just clone the Predis repository. Otherwise, you need to download the ZIP archive and unzip it.

gafitescu@ubun2:~$ /usr/local/bin/redis-server
* The server is now ready to accept connections on port 6379

To test everything, create a test.php file with the following to test if you can successfully connect to a running Redis server using Predis:

gafitescu@ubun2:~$ git clone git://github.com/nrk/predis.git

When you run it, you should see the message "Successfully connected to Redis".

Using Redis

In this section, you will outline most of the commonly used commands provided by Redis. Memcache has equivalents for most commands, so if you are familiar with Memcache, this list will look familiar.

SET, GET and EXISTS

The most commonly used commands in Redis are SET, GET, and EXISTS. You can use these commands to store and check temporary information that will be accessed multiple times, usually in key-value ways. For example:

<?php
require "predis/autoload.php";
PredisAutoloader::register();

// 由于我们连接到默认设置localhost
// 和6379端口,因此无需额外的
// 配置。如果不是,则可以将
// 方案、主机和端口指定为数组
// 传递给构造函数。
try {
    $redis = new Predis\Client();
/*
    $redis = new Predis\Client(array(
        "scheme" => "tcp",
        "host" => "127.0.0.1",
        "port" => 6379));
*/
    echo "Successfully connected to Redis";
}
catch (Exception $e) {
    echo "Couldn't connected to Redis";
    echo $e->getMessage();
}
The

set() method is used to set the value to a specific key. In this example, the key is "hello_world" and the value is "Hi from php!". The get() method retrieves the value of the key, and in this case it is "hello_world". The exists() method reports whether the provided key is found in the Redis store. Keys are not limited to alphanumeric characters and underscores. The following will also be valid:

<?php
$redis->set("hello_world", "Hi from php!");
$value = $redis->get("hello_world");
var_dump($value);

echo ($redis->exists("Santa Claus")) ? "true" : "false";

INCR (INCRBY) and DECR (DECRBY)

INCR and DECR commands are used to increment and decrement values ​​and are a good way to maintain counters. INCR and DECR increment/decrement their value by 1; you can also adjust with INCRBY and DECRBY at larger intervals. Here is an example:

<?php
$redis->set("I 2 love Php!", "Also Redis now!");
$value = $redis->get("I 2 love Php!");

Redis data type

As I mentioned before, Redis has built-in data types. You might think it's weird to have data types in a NoSQL key-value storage system like Redis, but this is useful for developers to organize information more efficiently and perform specific actions, which is usually faster when data typed. The data type of Redis is:

  • String - The basic data type used in Redis, from which you can store a small number of characters to the contents of the entire file.
  • List - A simple list of strings arranged in the order in which their elements are inserted. You can add and remove elements from the head and tail of a list, so you can use this data type to implement a queue.
  • Hash - Map of string keys and string values. This way you can represent an object (that can be considered as a level one-level depth JSON object).
  • Collection - An unordered collection of strings where you can add, delete and test the presence of members. The only constraint is that you do not allow duplicate members.
  • Sorting sets—Special case of collection data types. The difference is that each member has an associated score that is used to sort the set from the smallest score to the maximum score.

So far I've only demonstrated strings, but there are some commands that make it equally easy to use data from other data types.

HSET, HGET and HGETALL, HINCRBY and HDEL

These commands are used to handle the hash data type of Redis:

  • HSET—Set the value of the key on the hash object.
  • HGET - Get the value of the key on the hash object.
  • HINCRBY—Increment the value of the hash object's key using the specified value.
  • HDEL - Remove key from object.
  • HGETALL - Get all keys and data of the object.

Here is an example to demonstrate its usage:

gafitescu@ubun2:~$ /usr/local/bin/redis-server
* The server is now ready to accept connections on port 6379

Summary

In this article, we've only covered a short list of Redis commands, but you can view the full list of commands on the Redis website. In fact, Redis offers much more than just a replacement for Memcache. Redis will last; it has a growing community, support for all major languages, and provides persistence and high availability through master-slave replication. Redit is open source, so if you are a C language expert, you can fork its source code from GitHub and become a contributor. If you want to learn more than the project website, you might want to consider checking out two excellent Redis books, Redis Cookbook and Redis: The Definitive Guide.

Frequently Asked Questions about Redis with Predis in PHP

  • What is the main purpose of using Predis and Redis in PHP?

Predis is a flexible and fully functional PHP Redis client library. It allows PHP developers to interact with Redis using PHP code, making it easier to use Redis in PHP applications. Predis provides a simple and intuitive API to handle Redis, and it supports a variety of Redis functions, including transactions, pipelines, and clusters. By using Predis, PHP developers can take advantage of the power of Redis in their applications without having to deal with the complexity of directly interacting with the Redis server.

  • How to install Predis in PHP project?

Predis can be easily installed in PHP projects using Composer (PHP's dependency management tool). You can install Predis by running the following command in the root directory of your project: composer require predis/predis. This command will download and install the latest stable version of Predis and its dependencies into your project.

  • How to use Predis to connect to a Redis server?

To connect to the Redis server using Predis, you need to create a new instance of the PredisClient class and pass the connection parameters to its constructor. The connection parameter can be a string representing the Redis server URI or an associative array containing connection options. Here is an example:

gafitescu@ubun2:~$ git clone git://github.com/nrk/predis.git

In this example, the client will connect to the Redis server running on localhost port 6379.

  • How to use Predis to execute Redis commands?

Predis provides methods for executing all Redis commands. These methods are named after the corresponding Redis command, which accept command parameters as parameters. For example, to set key-value pairs in Redis, you can use the set method as follows:

<?php
require "predis/autoload.php";
PredisAutoloader::register();

// 由于我们连接到默认设置localhost
// 和6379端口,因此无需额外的
// 配置。如果不是,则可以将
// 方案、主机和端口指定为数组
// 传递给构造函数。
try {
    $redis = new Predis\Client();
/*
    $redis = new Predis\Client(array(
        "scheme" => "tcp",
        "host" => "127.0.0.1",
        "port" => 6379));
*/
    echo "Successfully connected to Redis";
}
catch (Exception $e) {
    echo "Couldn't connected to Redis";
    echo $e->getMessage();
}

To get the value of the key, you can use the get method:

gafitescu@ubun2:~$ /usr/local/bin/redis-server
* The server is now ready to accept connections on port 6379
  • How to handle errors in Predis?

Predis will throw an exception when the Redis command fails. These exceptions are instances of the PredisResponseServerException class or its subclass. You can catch these exceptions and handle errors in your code. Here is an example:

gafitescu@ubun2:~$ git clone git://github.com/nrk/predis.git

In this example, if the set command fails, the catch block will be executed and an error message will be printed.

(The answers to the other questions are similar to the previous output, except that the wording is slightly adjusted, and we will not repeat it here)

The above is the detailed content of An Introduction to Redis in PHP using Predis. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Debunking the Myths: Is PHP Really a Dead Language?Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AM

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

The PHP vs. Python Debate: Which is Better?The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.