Cara menggunakan php session cookie samesite

Sessions and cookies allow data to be persisted across multiple user requests. In plain PHP you may access them through the global variables $_SESSION and $_COOKIE, respectively. Yii encapsulates sessions and cookies as objects and thus allows you to access them in an object-oriented fashion with additional useful enhancements.

Sessions

Like requests and responses, you can get access to sessions via the session application component which is an instance of yii\web\Session, by default.

Opening and Closing Sessions

To open and close a session, you can do the following:

You can call and multiple times without causing errors; internally the methods will first check if the session is already open.

Accessing Session Data

To access the data stored in session, you can do the following:

Info: When you access session data through the session component, a session will be automatically opened if it has not been done so before. This is different from accessing session data through $_SESSION, which requires an explicit call of

createTable('{{%session}}', [
            'id' => $this->char(64)->notNull(),
            'expire' => $this->integer(),
            'data' => $this->binary()
        ]);
        $this->addPrimaryKey('pk-id', '{{%session}}', 'id');
    }

    public function down()
    {
        $this->dropTable('{{%session}}');
    }
}
0.

When working with session data that are arrays, the session component has a limitation which prevents you from directly modifying an array element. For example,

You can use one of the following workarounds to solve this problem:

For better performance and code readability, we recommend the last workaround. That is, instead of storing an array as a single session variable, you store each array element as a session variable which shares the same key prefix with other array elements.

Custom Session Storage

The default yii\web\Session class stores session data as files on the server. Yii also provides the following session classes implementing different session storage:

All these session classes support the same set of API methods. As a result, you can switch to a different session storage class without the need to modify your application code that uses sessions.

Note: If you want to access session data via $_SESSION while using custom session storage, you must make sure that the session has already been started by . This is because custom session storage handlers are registered within this method.

Note: If you use a custom session storage you may need to configure the session garbage collector explicitly. Some installations of PHP (e.g. Debian) use a garbage collector probability of 0 and clean session files offline in a cronjob. This process does not apply to your custom storage so you need to configure yii\web\Session::$GCProbability to use a non-zero value.

To learn how to configure and use these component classes, please refer to their API documentation. Below is an example showing how to configure yii\web\DbSession in the application configuration to use a database table for session storage:

You also need to create the following database table to store session data:

CREATE TABLE session
(
    id CHAR(40) NOT NULL PRIMARY KEY,
    expire INTEGER,
    data BLOB
)

where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB types that can be used for some popular DBMS:

  • MySQL: LONGBLOB
  • PostgreSQL: BYTEA
  • MSSQL: BLOB

Note: According to the php.ini setting of

createTable('{{%session}}', [
            'id' => $this->char(64)->notNull(),
            'expire' => $this->integer(),
            'data' => $this->binary()
        ]);
        $this->addPrimaryKey('pk-id', '{{%session}}', 'id');
    }

    public function down()
    {
        $this->dropTable('{{%session}}');
    }
}
3, you may need to adjust the length of the
createTable('{{%session}}', [
            'id' => $this->char(64)->notNull(),
            'expire' => $this->integer(),
            'data' => $this->binary()
        ]);
        $this->addPrimaryKey('pk-id', '{{%session}}', 'id');
    }

    public function down()
    {
        $this->dropTable('{{%session}}');
    }
}
4 column. For example, if
createTable('{{%session}}', [
            'id' => $this->char(64)->notNull(),
            'expire' => $this->integer(),
            'data' => $this->binary()
        ]);
        $this->addPrimaryKey('pk-id', '{{%session}}', 'id');
    }

    public function down()
    {
        $this->dropTable('{{%session}}');
    }
}
5, you should use a length 64 instead of 40.

Alternatively, this can be accomplished with the following migration:

createTable('{{%session}}', [
            'id' => $this->char(64)->notNull(),
            'expire' => $this->integer(),
            'data' => $this->binary()
        ]);
        $this->addPrimaryKey('pk-id', '{{%session}}', 'id');
    }

    public function down()
    {
        $this->dropTable('{{%session}}');
    }
}

Flash Data

Flash data is a special kind of session data which, once set in one request, will only be available during the next request and will be automatically deleted afterwards. Flash data is most commonly used to implement messages that should only be displayed to end users once, such as a confirmation message displayed after a user successfully submits a form.

You can set and access flash data through the session application component. For example,

Like regular session data, you can store arbitrary data as flash data.

When you call , it will overwrite any existing flash data that has the same name. To append new flash data to an existing message of the same name, you may call instead. For example:

Note: Try not to use together with for flash data of the same name. This is because the latter method will automatically turn the flash data into an array so that it can append new flash data of the same name. As a result, when you call , you may find sometimes you are getting an array while sometimes you are getting a string, depending on the order of the invocation of these two methods.

Tip: For displaying Flash messages you can use yii\bootstrap\Alert widget in the following way:

echo Alert::widget([
   'options' => ['class' => 'alert-info'],
   'body' => Yii::$app->session->getFlash('postDeleted'),
]);

Cookies

Yii represents each cookie as an object of yii\web\Cookie. Both yii\web\Request and yii\web\Response maintain a collection of cookies via the property named

createTable('{{%session}}', [
            'id' => $this->char(64)->notNull(),
            'expire' => $this->integer(),
            'data' => $this->binary()
        ]);
        $this->addPrimaryKey('pk-id', '{{%session}}', 'id');
    }

    public function down()
    {
        $this->dropTable('{{%session}}');
    }
}
7. The cookie collection in the former represents the cookies submitted in a request, while the cookie collection in the latter represents the cookies that are to be sent to the user.

The part of the application dealing with request and response directly is controller. Therefore, cookies should be read and sent in controller.

Reading Cookies

You can get the cookies in the current request using the following code:

Sending Cookies

You can send cookies to end users using the following code:

Besides the , properties shown in the above examples, the yii\web\Cookie class also defines other properties to fully represent all available cookie information, such as , . You may configure these properties as needed to prepare a cookie and then add it to the response's cookie collection.

When you are reading and sending cookies through the

createTable('{{%session}}', [
            'id' => $this->char(64)->notNull(),
            'expire' => $this->integer(),
            'data' => $this->binary()
        ]);
        $this->addPrimaryKey('pk-id', '{{%session}}', 'id');
    }

    public function down()
    {
        $this->dropTable('{{%session}}');
    }
}
8 and
createTable('{{%session}}', [
            'id' => $this->char(64)->notNull(),
            'expire' => $this->integer(),
            'data' => $this->binary()
        ]);
        $this->addPrimaryKey('pk-id', '{{%session}}', 'id');
    }

    public function down()
    {
        $this->dropTable('{{%session}}');
    }
}
9 components as shown in the last two subsections, you enjoy the added security of cookie validation which protects cookies from being modified on the client-side. This is achieved by signing each cookie with a hash string, which allows the application to tell if a cookie has been modified on the client-side. If so, the cookie will NOT be accessible through the of the
createTable('{{%session}}', [
            'id' => $this->char(64)->notNull(),
            'expire' => $this->integer(),
            'data' => $this->binary()
        ]);
        $this->addPrimaryKey('pk-id', '{{%session}}', 'id');
    }

    public function down()
    {
        $this->dropTable('{{%session}}');
    }
}
8 component.

Note: Cookie validation only protects cookie values from being modified. If a cookie fails the validation, you may still access it through $_COOKIE. This is because third-party libraries may manipulate cookies in their own way, which does not involve cookie validation.

Cookie validation is enabled by default. You can disable it by setting the property to be

echo Alert::widget([
   'options' => ['class' => 'alert-info'],
   'body' => Yii::$app->session->getFlash('postDeleted'),
]);
2, although we strongly recommend you do not do so.

Note: Cookies that are directly read/sent via $_COOKIE and

echo Alert::widget([
   'options' => ['class' => 'alert-info'],
   'body' => Yii::$app->session->getFlash('postDeleted'),
]);
4 will NOT be validated.

When using cookie validation, you must specify a that will be used to generate the aforementioned hash strings. You can do so by configuring the

createTable('{{%session}}', [
            'id' => $this->char(64)->notNull(),
            'expire' => $this->integer(),
            'data' => $this->binary()
        ]);
        $this->addPrimaryKey('pk-id', '{{%session}}', 'id');
    }

    public function down()
    {
        $this->dropTable('{{%session}}');
    }
}
8 component in the application configuration:

return [
    'components' => [
        'request' => [
            'cookieValidationKey' => 'fill in a secret key here',
        ],
    ],
];

Info: is critical to your application's security. It should only be known to people you trust. Do not store it in the version control system.

Security settings

Both yii\web\Cookie and yii\web\Session support the following security flags:

httpOnly

For better security, the default value of and the 'httponly' parameter of is set to

echo Alert::widget([
   'options' => ['class' => 'alert-info'],
   'body' => Yii::$app->session->getFlash('postDeleted'),
]);
6. This helps mitigate the risk of a client-side script accessing the protected cookie (if the browser supports it). You may read the HttpOnly wiki article for more details.

secure

The purpose of the secure flag is to prevent cookies from being sent in clear text. If the browser supports the secure flag it will only include the cookie when the request is sent over a secure (TLS) connection. You may read the SecureFlag wiki article for more details.

sameSite

Starting with Yii 2.0.21 the setting is supported. It requires PHP version 7.3.0 or higher. The purpose of the

echo Alert::widget([
   'options' => ['class' => 'alert-info'],
   'body' => Yii::$app->session->getFlash('postDeleted'),
]);
7 setting is to prevent CSRF (Cross-Site Request Forgery) attacks. If the browser supports the
echo Alert::widget([
   'options' => ['class' => 'alert-info'],
   'body' => Yii::$app->session->getFlash('postDeleted'),
]);
7 setting it will only include the cookie according to the specified policy ('Lax' or 'Strict'). You may read the SameSite wiki article for more details. For better security, an exception will be thrown if
echo Alert::widget([
   'options' => ['class' => 'alert-info'],
   'body' => Yii::$app->session->getFlash('postDeleted'),
]);
7 is used with an unsupported version of PHP. To use this feature across different PHP versions check the version first. E.g.

[
    'sameSite' => PHP_VERSION_ID >= 70300 ? yii\web\Cookie::SAME_SITE_LAX : null,
]

Note: Since not all browsers support the

echo Alert::widget([
   'options' => ['class' => 'alert-info'],
   'body' => Yii::$app->session->getFlash('postDeleted'),
]);
7 setting yet, it is still strongly recommended to also include .

Session php.ini settings

As noted in PHP manual,

return [
    'components' => [
        'request' => [
            'cookieValidationKey' => 'fill in a secret key here',
        ],
    ],
];
1 has important session security settings. Please ensure recommended settings are applied. Especially
return [
    'components' => [
        'request' => [
            'cookieValidationKey' => 'fill in a secret key here',
        ],
    ],
];
2 that is not enabled by default in PHP installations. This setting can also be set with .

Perbedaan antara session dan cookie yaitu, session menyimpan data pada sisi server sedangkan cookie menyimpan data pada sisi client dan karena itulah session lebih aman dalam menyimpanan data maupun file dibanding cookie karena penyimpanan dilakukan di sisi server.

Apa manfaat dari penggunaan session dan cookies pada aplikasi web?

Adapun session cookie hanya digunakan saat menavigasi situs web. Cookie ini berguna untuk mengenali pengguna saat aktivitas online berlangsung.