php-Session
<Beginner PHP><Array><Loop><Function><Pre-Def variable><Session><Read Write File><CRUD>
$_SESSION
With it you can store info in variables, to be used across multiple pages
Info is not stored on the user`s computer ( <> cookies).
Session variables last until the user closes the browser
Session starts using the session_start() function
The we set session variables with $_SESSION
<?php
session_start();
$_SESSION['color']="red";
$_SESSION['name']="John";
?>
now color and name session variables are accessible on multiple pages(until end of session)
Session start must be before any html tags.
Another page accessing session variables
<?php
session_start();
?></head><body>
<?php
echo "your name is:".$_SESSION['name'];
?>
</body></html>
session_unset() : removes variable
session_destroy : destroy session
COOKIE
it identifies the user
it is a small file embeded in user computer
it is sent each time the page is requested
PHP creates and retrieves cookie values
Creating cookies
setcookie(name, value, expire, path, domain, secure, httponly);
- name: required , cookie name
- value: cookie`s value
- expire: when the cookie expires. 86400*30 menas 30 days. If omitted default is 0 (expire on end of session)
- path: server path of the cookie. if set to "/" then cookie available within entire domain. "/php": within php directory and sub directory. Default is current directory.
- domain: cookie`s domain name.Example.com : available on all subdomain of example.com
- secure: cookie transmitted over secure HTTPS connection or not. TRUE: cookie is set only if secure connection exist. Default is FALSE.
- httponly: cookie accessible through HTTP protocol only or not. TRUE: accessible through HTTP protocol and not accessible to scripting language. Reduce identity theft using XSS attacks. Default is FALSE.
Creating Cookie code:
<?php
$ value = "John";
setcookie("user",$value,time()+(86400*30),'/');
Find out if cookie is set:
if(isset($_COOKIE['user'])){
echo "value is:".$_COOKIE['user'];
}
?>
Note: Never store sensitive data in cookies. Also respect regional regulations and user preference when using cookies, sometimes you may not use it at all.
Comments
Post a Comment