unknown time to read, 1.84K views since 2016.10.09

Cookies and session

Cookie and session are very powerfull instruments which are provided with php by default. With help of session and cookies you can make different services like shop carts, saving user state, authorization, caching and others. Cookies are binded to concrete domain, you can't reach cokkies for domain x, with script on domain y.

working with cookies in php

Cookies is a mechanism of storing some website information (user identificator, credentials, last viewed products, eg) on clients side. Generally its a http feature, also it has support in php.

reading a cookie

To read a cookie in a php you need to use superglobal array variable $_COOKIE. Each index of an array coresponds tothe appropriate cookie.

For example $_COOKIE['login'] would contain textual representation of cookie's login value.

You can see all your cookies for current domain by next code

print_r($_COOKIE);

setting a cookie in php

Attention! All cookies should be sent before any output to browser. Why? - the answer is simple: all cookies are writtenas an http header. And when the php make some output, for example to browser, all headers already written. If you need more explanation, please ask me to write an explanation article on this mechanism in comments to this post.

Some people store list of viewed items on their shop in cookies. Strange, but its their choice. For such tasks you need to write a cookie. Use a setcookie function for that:


$itemsViewed = [];
If (isset($_COOKIE['viewed'])) {
    $itemsViewed = explode(',',$_COOKIE['viewed']); // it's not safe, only for example here
}

$name = 'viewed';// name of a cookie
$value = implode(',',$itemsViewed); // value of a cookie
$expiry = time()+3600; // expire time of a cookie
$path = '/'; // you can set different cookies with the same name for different uri paths. 

setcookie($name,$value,$expiry,$path);

working with session in php

Architecture of handling requests data in php called share nothing architectire because php works in a client server conditions: Each request for the php is not personalized - you can't say if the client with same ip and browser (data whicn could be investigated from request) is the same person. It could be another person just sharing the same wifi connection with previous one.

Thats why client server languages has such thing as session - mechanism to personalize number of requests from client in some time range. In fact, session mechanism is done by the help of cookies - some unique id is writen to client's cookie when the client first time visit your script ( when the sessionis firstly start) and then, each next request client carries that session id in cookies, so php session mechanism can store some data for each session (unique id)

By default, sessions in php do not start automatically. In order to use sessionsandtheir storage of data you need to start them on each page you going to use sessions:

<?php

session_start(); // after this point your superglobal session array is personalized

$_SESSION['name'] = 'john';

value of $_SESSION can be used on other pages along current session. its personalized and belong only to current client. To remove data from session you can use default features of php to remove variables:

<?php

session_start();
unset($_SESSION['name']); // this removes data from cureent session

Attention! Sessions use files to store data for users. Each script with session usage blocks another current session requests before current closes. What this means? If you have a long process (tens of secconds) on some page with session started you won't be able to run another script with session (for example in another tab) until current page finishes request. Example: one user opens two pages one after another - second opened page would be waiting when the first finishes request. To avoid such situations you can use session_write_close function (if you don't need to use write to session):

<?php

session_start();

// some actions with session

session_write_close();

// long process
Read next article Objects and classes in course Basic PHP