What is the difference between a session and cookies in PHP?
Session V/S Cookies
Cookie is an array of data stored by the browser on client location and sent to the server with every request. It store limited amount of data about 4kb(i.e.: 4096 bytes). It is less secure than session because it present in client's computer.
Session is an array of data stored on the server and associated with a given user (usually via a cookie containing an id code). It store unlimited amount of data. It is more secure because of stored on the server.
Example of Cookie
<?php setcookie(name, value, expire, path, domain, secure, httponly); $cookie_uname = "user"; $cookie_uvalue= "Retesh Kumar"; //set cookies for 1 hour time setcookie($cookie_uname, $cookie_uvalue, 3600, "/"); //expire cookies setcookie($cookie_uname,"",-3600); ?>
Example of Session
<?php session_start(); //session variable $_SESSION['user'] = 'Retesh'; //destroyed the entire sessions session_destroy(); //Destroyed the session variable "user". unset($_SESSION['user']); ?>
Important Interview Question