IWD - Unit 4 - Part 2 - Cookies & Sessions
IWD - Unit 4 - Part 2 - Cookies & Sessions
⚫ Cookies (that are saved in browser on the client system) can be viewed
through ‘Internet Settings’ in the browser.
⚫ Cookies can be created on the server side (through PHP script). They are
sent to the client system, where they can be saved and accessed in future.
⚫ Cookies can also be deleted from the client system (through PHP script).
⚫ Syntax:
setcookie(name, value, expiry, path, domain, security);
⚫ Only the name parameter is required. All other parameters are optional.
⚫ Example:
setcookie(‘user’, ‘hnt’, time()+3600, ‘/’, ‘’, 1);
⚫ Syntax:
$_COOKIE[‘cookiename’]; or $HTTP_COOKIE_VARS[‘cookiename’];
⚫ Example:
echo ‘Hello ’ . $_COOKIE[‘user’];
⚫ However, we can delete the cookie by setting the ‘expiry’ parameter to some
time in the past (instead of future) in the setcookie() function.
⚫ Example:
setcookie(‘user’, ‘’, time() – 3600);
⚫ Here, cookie is set to expire before 1 Hour. So, it automatically gets deleted.
⚫ Usually, a session (or a session variable) is created for a user when he/she
logs in (or access) a website and remains alive till he logs out (or the
browsing session ends).
⚫ This function first checks if a session is already started and refers to it. If no
session is started, then it starts a new one.
⚫ This function needs to be called on all the pages where a session variable is
needed to be created, modified, accessed or destroyed.
⚫ Then, a file is created in the temporary directory on the server with name
‘sess_uniquesessionid’ (for e.g. ‘sess_3c7foj34c3jj973hjkop2fc937e3443’).
⚫ Syntax:
$_SESSION[‘sessionvariablename’];
⚫ Example:
$_SESSION[‘username’] = ‘hnt’; //creates or modifies the session variable
echo $_SESSION[‘username’]; //prints the value of the session variable