[Yandex Cloud documentation](../../index.md) > [Yandex Managed Service for Valkey™](../index.md) > [Tutorials](index.md) > Storing PHP sessions in Yandex Managed Service for Valkey™

# Using a Yandex Managed Service for Valkey™ cluster as a PHP session storage


# Using a Yandex Managed Service for Valkey™ cluster as a PHP session storage


You can use Yandex Managed Service for Valkey™ clusters for storing PHP session data.

To configure a Yandex Managed Service for Valkey™ cluster as a PHP session storage:

1. [Configure PHP to use the Yandex Managed Service for Valkey™ cluster a session storage](#settings-php).
1. [Check whether PHP session data is saved to the Yandex Managed Service for Valkey™ cluster](#test-settings).

If you no longer need the resources you created, [delete them](#clear-out).


## Required paid resources {#paid-resources}

* Yandex Managed Service for Valkey™ target cluster: use of computing resources allocated to hosts, storage and backup size (see [Valkey™ pricing](../pricing.md)).
* Public IP addresses if public access is enabled for cluster hosts (see [Virtual Private Cloud pricing](../../vpc/pricing.md)).
* VM instance, which includes the use of computing resources, storage, public IP address, and OS (see [Compute Cloud pricing](../../compute/pricing.md)).


## Getting started {#before-you-begin}

### Set up your infrastructure {#deploy-infrastructure}

{% list tabs group=instructions %}

- Manually {#manual}

    
    1. If using Virtual Private Cloud security groups, [configure them](../../vpc/operations/security-group-add-rule.md). Add TCP rules to the security group to allow the following:

        * Incoming traffic on port `22` from any IP addresses for SSH.
        * Outgoing and incoming traffic on ports `80` and `443` to and from any IP address for HTTP/HTTPS.
        * Outgoing and incoming traffic on port `6379` to and from internal network IP addresses for Valkey™.

        For more information, see [Security groups](../../vpc/concepts/security-groups.md).


    1. [Create a VM with LAMP/LEMP](../../tutorials/web/lamp-lemp/console.md#create-vm) in Yandex Compute Cloud using any suitable configuration.

        
        When creating the VM, select the security group configured earlier. To check the security settings, enter the VM’s public IP address in your browser’s address bar: you should see the default page of the web server.


    1. [Create a Yandex Managed Service for Valkey™ cluster](../operations/cluster-create.md) with any suitable configuration. When creating the Yandex Managed Service for Valkey™ cluster, specify the same network and security groups as those of the VM hosting the web server.

- Terraform {#tf}

    1. If you do not have Terraform yet, [install it](../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform).
    1. [Get the authentication credentials](../../tutorials/infrastructure-management/terraform-quickstart.md#get-credentials). You can add them to environment variables or specify them later in the provider configuration file.
    1. [Configure and initialize a provider](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). There is no need to create a provider configuration file manually, you can [download it](https://github.com/yandex-cloud-examples/yc-terraform-provider-settings/blob/main/provider.tf).
    1. Place the configuration file in a separate working directory and [specify the parameter values](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). If you did not add the authentication credentials to environment variables, specify them in the configuration file.

    1. Download the configuration file matching your cluster type to the same working directory:

        * [redis-cluster-non-sharded-and-vm-for-php.tf](https://github.com/yandex-cloud-examples/yc-redis-as-php-session-storage/blob/main/redis-cluster-non-sharded-and-vm-for-php.tf): For a non-sharded cluster.
        * [redis-cluster-sharded-and-vm-for-php.tf](https://github.com/yandex-cloud-examples/yc-redis-as-php-session-storage/blob/main/redis-cluster-sharded-and-vm-for-php.tf): For a [sharded](../concepts/sharding.md) cluster.

        Each file describes the following:

        * Network.
        * Subnet.
        * Default security group and rules for connecting to your cluster and VM from the internet.
        * Yandex Managed Service for Valkey™ cluster.
        * Virtual machine.

    1. Specify the following in the configuration file:

        * Password to access the Yandex Managed Service for Valkey™ cluster.
        * Public LAMP/LEMP [image](../../compute/operations/images-with-pre-installed-software/get-list.md) ID.
        * Username and path to the [public key](../../compute/operations/vm-connect/ssh.md#creating-ssh-keys) for accessing the virtual machine. By default, the pre-configured image ignores the specified username and automatically creates a user named `ubuntu`. Use it to connect to the VM.

    1. Validate your Terraform configuration files using this command:

        ```bash
        terraform validate
        ```

        Terraform will display any configuration errors detected in your files.

    1. Create the required infrastructure:

        1. Run this command to view the planned changes:
        
           ```bash
           terraform plan
           ```
        
           If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
        
        1. If everything looks correct, apply the changes:
           1. Run this command:
        
              ```bash
              terraform apply
              ```
        
           1. Confirm updating the resources.
           1. Wait for the operation to complete.

        All the required resources will be created in the specified folder. You can check resource availability and their settings in the [management console](https://console.yandex.cloud).

{% endlist %}

### Configure additional settings {#additional-settings}

1. [Connect to the VM with the web server over SSH and configure it](../../compute/operations/vm-connect/ssh.md):

    * Install certificates:

        ```bash
        sudo mkdir --parents /usr/local/share/ca-certificates/Yandex/ && \
        sudo wget "https://storage.yandexcloud.net/cloud-certs/CA.pem" \
            --output-document /usr/local/share/ca-certificates/Yandex/YandexInternalRootCA.crt
        ```

    * Set up the environment and install the [phpredis](https://github.com/phpredis/phpredis) library using `pecl`:

        ```bash
        sudo apt update && \
        sudo apt install php-dev pkg-php-tools redis-tools --yes && \
        sudo pecl channel-update pecl.php.net && \
        sudo pecl install redis
        ```

    * Set yourself as the owner of the `/var/www/html/` directory and delete all its contents:

        ```bash
        sudo chown <username> /var/www/html/ --recursive && \
        rm /var/www/html/*
        ```

## Configure PHP to use the Yandex Managed Service for Valkey™ cluster as a session storage {#settings-php}

1. Edit the `php.ini` configuration file for your web server.

    `php.ini` is usually located in the following directory:

    * `/etc/php/7.2/apache2/` for Apache
    * `/etc/php/7.2/fpm/` for NGINX

    To find out the location of `php.ini`, run the `sudo find /etc/ -name php.ini` command.

    {% note info %}

    There is no need to make any changes to `php.ini` for the PHP CLI.

    {% endnote %}
    
    {% list tabs group=cluster %}

      - Non-sharded cluster {#non-sharded}

        ```ini
        [PHP]
        ...
        extension = redis
        ...
        [Session]
        session.save_handler = redis
        session.save_path = "tcp://<Valkey™_master_host_FQDN>:6379?auth=<password>"
        ```

      - Sharded cluster {#sharded}

        ```ini
        [PHP]
        ...
        extension = redis
        ...
        [Session]
        session.save_handler = rediscluster
        session.save_path = "seed[]=<FQDN1>:6379&seed[]=<FQDN2>:6379&seed[]=<FQDN3>:6379&auth=<password>"
        ```

        Where `<FQDN1>`, `<FQDN2>`, and `<FQDN3>` are fully qualified domain names of the [cluster’s master hosts](../operations/hosts.md#list). For example, for a cluster with three shards and password set to `password`, the `session.save_path` parameter value will look like this:

        ```ini
        session.save_path = "seed[]=rc1a-t9h8gxqo********.mdb.yandexcloud.net:6379&seed[]=rc1b-7qxk0h3b********.mdb.yandexcloud.net:6379&seed[]=rc1c-spy1c1i4********.mdb.yandexcloud.net:6379&auth=password"
        ```

    {% endlist %}

    For more information about connecting to a cluster, see [Pre-configuring a Valkey™ cluster connection](../operations/connect/index.md).

1. Restart the web server:

    * `sudo systemctl restart apache2` for Apache
    * `sudo systemctl restart php7.2-fpm` for NGINX

## Check whether PHP session data is saved to the Yandex Managed Service for Valkey™ cluster {#test-settings}

1. In the `/var/www/html/` directory, create a file named `index.php` to output powers of `2`:

    ```php
    <?php
    session_start();

    $count = isset($_SESSION['count']) ? $_SESSION['count'] : 1;

    echo $count;

    $_SESSION['count'] = $count * 2;
    ```

    Each time you refresh the page, the output value will increase. The `$count` variable value will be saved in the session data. Valkey™ will generate a unique key per session.

1. Connect to the Valkey™ cluster from your VM via `redis-cli`:

    ```bash
    redis-cli -c -h <master_host_FQDN> -a <password>
    ```

    Enter the following command to view the keys stored in Valkey™:

    ```text
    KEYS *
    ```

    ```text
    (empty list or set)
    ```

    The returned result shows that no data is currently stored in Valkey™.

1. Check whether user sessions are saved when connecting to the web server:

    1. Enter the public IP of the VM hosting the web server in your browser’s address bar. The first time you open the page, `1` will be output.
    1. Refresh the page several times: the output value will increase.
    1. Open the page in a different browser: the count will start from `1`.
    1. Refresh the page several times: the output value will also increase.

    The fact that the `$count` variable value continues to increment correctly between browser page refreshes shows that the configured PHP session storage setup in the Yandex Managed Service for Valkey™ cluster works properly.

1. Repeat the command to list all keys stored in Valkey™:

    ```text
    KEYS *
    ```

    ```text
    1) "PHPREDIS_SESSION:keb02haicgi0ijeju3********"
    2) "PHPREDIS_SESSION:c5r0mbe1v84pn2b5kj********"
    ```

    The returned result shows that each session in Valkey™ has its own unique key.

## Delete the resources you created {#clear-out}

Delete the resources you no longer need to avoid paying for them:

{% list tabs group=instructions %}

- Manually {#manual}

    * [Delete the Yandex Managed Service for Valkey™ cluster](../operations/cluster-delete.md).
    * [Delete the VM](../../compute/operations/vm-control/vm-delete.md).
    * If you reserved public static IP addresses, release and [delete them](../../vpc/operations/address-delete.md).

- Terraform {#tf}

    1. In the terminal window, go to the directory containing the infrastructure plan.
    
        {% note warning %}
    
        Make sure the directory has no Terraform manifests with the resources you want to keep. Terraform deletes all resources that were created using the manifests in the current directory.
    
        {% endnote %}
    
    1. Delete resources:
    
        1. Run this command:
    
            ```bash
            terraform destroy
            ```
    
        1. Confirm deleting the resources and wait for the operation to complete.
    
        All the resources described in the Terraform manifests will be deleted.

{% endlist %}