COOKIE AND SESSION IN PHP COOKIES Like variable

COOKIE AND SESSION IN PHP

COOKIES Like variable Stores single piece of data under a unique name Browser dependent stores cookies on user’s browser Moves page to page Avoids the problem to log in every time Always stored as text

COOKIES WITH PHP Set cookie setcookie() stores data in cookies Syntax: setcookie(“cookie name”, ”value”); Accepts an optional third argument Sets the expiration date of the cookie E. g: setcookie(‘username’, ‘aacssh’, time()+(60 * 60)); Sets expiration date 1 hour (60 sec * 60 min) from the current time Retrieve cookie using super global using $_COOKIE E. g: $_COOKIE[‘cookie name’];

(CONT…) Delete cookie Set expiration date to time in the past Syntax: setcookie(‘username’, ’aacssh’, time()-3600); Set time in the past

SESSION Time spend by user at web application Stores small piece of data on server More secure and more reliable Automatically destroyed by shutting down the browser Stored in session variable

SESSION WITH PHP Starting session Started by function session_start() Allow data to store in session variables Should be the first line of code End session Close session with session_destroy()

(CONT…) Session variables Set session variable with super global $_SESSION Once created , gets stored on the server E. g: $_SESSION[‘variable’] = value; Variable = name of session Delete session variables manually Not automatically deleted when session is destroyed Set $_SESSION superglobal to an empty array E. g: $_SESSION = array();

HOW PHP SESSION WORKS

USING BOTH SESSION AND COOKIE Sessions have short life Cookie can last forever Long enough to outlast a session If session uses cookie to remember session id Cookie id is name after the session i. e session_name() To close session, cookie must also be deleted

SOMETHING MORE…. . Header function Tells the server to send a new page Syntax: header(“Location: URL”);

CODE SNAPSHOTS : 1. Combining session and cookie 1. Creates session and cookie

CONTD… session. php file Separate file that is required in every php file.

CONTD Logout. php Destroies sessions and cookies

Lets make a simple login system
- Slides: 14