How to Secure Cookie in PHP using Session

An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.

But now you want to set permissions on these session variables or values to accessing on other folder or page.for this you want to set the session cookie parameters.

Set the session cookie parameters PHP have function:



Parameters :

lifetime – Lifetime of the session cookie, defined in seconds.
path – Path on the domain where the cookie will work. Use a single slash (‘/’) for all paths on the domain.
domain – Cookie domain, for example ‘’. To make cookies visible on all subdomains then the domain must be prefixed with a dot like ‘’.
secure – If TRUE cookie will only be sent over secure connections.
httponly – If set to TRUE then PHP will attempt to send the httponly flag when setting the session cookie.

void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )


Example :

if (ini_get("session.use_cookies")) {
    session_set_cookie_params(0, '/abc/xyz/', '', false, true);

In above example says now values of cookies that will be created anywhere inside the page of abc/xyz folder will be accessable only inside abc/xyz folder not in other folder present anywhere on server.

This function has not returned any value and you need to call session_set_cookie_params() for every request and before session_start() is called.

Get the session cookie parameters :

To get the session cookie parameters PHP have function


Returns an array with the current session cookie information, the array contains the following items:

lifetime – The lifetime of the cookie in seconds.
path – The path where information is stored.
domain – The domain of the cookie.
secure – The cookie should only be sent over secure connections.
httponly – The cookie can only be accessed through the HTTP protocol.

Example :

if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();

$params returned array with 5 parameters as listed above.

Leave a Comment