PHP-language, sessions Teppo Räisänen Principal Lecturer Oulu University of Applied Sciences School of Business and Information Management
Why sessions? InternetServer (e. g. oamk.fi) HTTP-Request (X)HTML presented by the browser (X)HTML processed by the server HTTP-Reply Browser
Why sessions? Because of HTTP-protocol No continuous connection between browser and server Often we need to know previous actions and information is our web-application (e. g. NetBank) NetBank
Lifecyckle of a session time loginpage 1page 2page nlogout entry exit session
Sessions Is identified by session ID Preserve data between multiple calls Information about a session is stored to server (e.g. to memory, file or database Session ID storing and propagation – HTTP GET – Cookie
Sessions in PHP Use following functions and superglobals – session_start() – $_SESSION[] – session_destroy() – unset() – …
Session_start() Is used in EVERY page where session variables are needed in your applications Has to be the FIRST line in your source code, otherwise...
Session variables Place where to store information that can be read and write during session In PHP you use superglobal $_SESSION[]
$_SESSION[] To read and write session spesific information $_SESSION[’mySessionVar’]=$somevariable; $somevariable=$_SESSION[’mySessionVar’];
Session_destroy() Destroy session and all session spesific variables Used e.g. when user logs out from your application If there is login, you should ALWAYS have logout
Checking for SESSION-variable To check if there is spesific session variable use isset()- function Example: if isset($_SESSION[’somevariable’]) { print ”Session variable is set!”; } else { print ”Session variable is not set!”; }
Resources p p