|
| 1 | +--- |
| 2 | +categories: |
| 3 | +- docs |
| 4 | +- develop |
| 5 | +- stack |
| 6 | +- oss |
| 7 | +- rs |
| 8 | +- rc |
| 9 | +- oss |
| 10 | +- kubernetes |
| 11 | +- clients |
| 12 | +description: Connect your PHP application to a Redis database |
| 13 | +linkTitle: Predis (PHP) |
| 14 | +title: Predis guide (PHP) |
| 15 | +weight: 8 |
| 16 | +--- |
| 17 | + |
| 18 | +[`Predis`](https://github.com/predis/predis) is the recommended [PHP](https://php.net/) |
| 19 | +client for Redis. |
| 20 | +The sections below explain how to install `Predis` and connect your application to a Redis database. |
| 21 | + |
| 22 | +{{< note >}}Although we provide basic documentation for `Predis`, it is a third-party |
| 23 | +client library and is not developed or supported directly by Redis. |
| 24 | +{{< /note >}} |
| 25 | + |
| 26 | +`Predis` requires a running Redis or |
| 27 | +[Redis Stack]({{< relref "/operate/oss_and_stack/install/install-stack/" >}}) server. |
| 28 | +See [Getting started]({{< relref "/operate/oss_and_stack/install/" >}}) for Redis installation |
| 29 | +instructions. |
| 30 | + |
| 31 | +## Install |
| 32 | + |
| 33 | +Use [Composer](https://getcomposer.org/) to install the `Predis` library |
| 34 | +with the following command line: |
| 35 | + |
| 36 | +```bash |
| 37 | +composer require predis/predis |
| 38 | +``` |
| 39 | + |
| 40 | +## Connect and test |
| 41 | + |
| 42 | +Connect to a locally-running server on the standard port (6379) |
| 43 | +with the following code: |
| 44 | + |
| 45 | +```php |
| 46 | +<?php |
| 47 | + |
| 48 | +require 'vendor/autoload.php'; |
| 49 | + |
| 50 | +use Predis\Client as PredisClient; |
| 51 | + |
| 52 | +$r = new PredisClient(); |
| 53 | +``` |
| 54 | + |
| 55 | +Store and retrieve a simple string to test the connection: |
| 56 | + |
| 57 | +```php |
| 58 | +echo $r->set('foo', 'bar'), PHP_EOL; |
| 59 | +// >>> OK |
| 60 | + |
| 61 | +echo $r->get('foo'), PHP_EOL; |
| 62 | +// >>> bar |
| 63 | +``` |
| 64 | + |
| 65 | +Store and retrieve a [hash]({{< relref "/develop/data-types/hashes" >}}) |
| 66 | +object: |
| 67 | + |
| 68 | +```php |
| 69 | +$r->hset('user-session:123', 'name', 'John'); |
| 70 | +$r->hset('user-session:123', 'surname', 'Smith'); |
| 71 | +$r->hset('user-session:123', 'company', 'Redis'); |
| 72 | +$r->hset('user-session:123', 'age', 29); |
| 73 | + |
| 74 | +echo var_export($r->hgetall('user-session:123')), PHP_EOL; |
| 75 | +/* >>> |
| 76 | +array ( |
| 77 | + 'name' => 'John', |
| 78 | + 'surname' => 'Smith', |
| 79 | + 'company' => 'Redis', |
| 80 | + 'age' => '29', |
| 81 | +) |
| 82 | +*/ |
| 83 | +``` |
| 84 | + |
| 85 | +## More information |
| 86 | + |
| 87 | +The [Predis wiki on Github](https://github.com/predis/predis/wiki) has |
| 88 | +information about the different connection options you can use. |
| 89 | + |
| 90 | +See also the pages in this section for more information and examples: |
0 commit comments