Current Location: Home> Latest Articles> Comprehensive Guide to Handling Cookies with Controllers in the Yii Framework

Comprehensive Guide to Handling Cookies with Controllers in the Yii Framework

M66 2025-06-07

How to Manage Cookies Using Controllers in the Yii Framework

Cookies are a common mechanism in web development used to store and transfer data between the server and the client. In the Yii framework, managing cookies through controllers is a clean and effective approach. This guide walks you through the process of creating, reading, updating, and deleting cookies using Yii's controller methods.

1. Creating a Cookie

In Yii, you can create a new cookie using controller logic. Here's a basic example:

public function actionSetCookie()
{
    $cookie = new yii\web\Cookie([
        'name' => 'username',
        'value' => 'John',
        'expire' => time() + 3600, // Expires in 1 hour
    ]);

    Yii::$app->response->cookies->add($cookie);
}

This code creates a cookie named username with a value of John that expires in one hour.

2. Reading a Cookie

To read a cookie, use the request component to access the cookies collection and check for the desired name:

public function actionGetCookie()
{
    $cookies = Yii::$app->request->cookies;

    if ($cookies->has('username')) {
        $username = $cookies->getValue('username');
        echo "Welcome back, $username!";
    } else {
        echo "No cookie found.";
    }
}

This function checks whether a cookie named username exists. If it does, it retrieves and displays the value; otherwise, it notifies that no cookie was found.

3. Updating a Cookie

To update a cookie, simply create a new one with the same name and add it again. Here's how:

public function actionUpdateCookie()
{
    $cookie = new yii\web\Cookie([
        'name' => 'username',
        'value' => 'Jane',
        'expire' => time() + 3600, // Still valid for 1 hour
    ]);

    Yii::$app->response->cookies->add($cookie);
}

By re-adding a cookie with the same name, you effectively update its value.

4. Deleting a Cookie

To remove a cookie, use Yii's remove() method:

public function actionDeleteCookie()
{
    Yii::$app->response->cookies->remove('username');
}

This method deletes the username cookie from the browser.

Conclusion

Managing cookies using Yii controllers is straightforward and efficient. With the provided methods and examples, developers can seamlessly implement cookie operations in their PHP web applications, enhancing user experience and maintaining clean session handling logic.