Tuesday, May 10, 2016

PHP Session & Cookies

PHP Session and Cookies

A cookie is are a mechanism for storing data in the remote browser and thus tracking or identifying return users. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.

Syntax

A cookie is created with the setcookie() function.
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.

Setting new cookie
=============================
<?php
setcookie
("name","value",time()+$int);/*name is your cookie's name
value is cookie's value
$int is time of cookie expires*/
?>
Getting Cookie
=============================
<?php echo $_COOKIE["your cookie name"];?>
Updating Cookie
=============================
<?php
setcookie
("color","red");
echo 
$_COOKIE["color"];/*color is red*/
/* your codes and functions*/
setcookie("color","blue");
echo 
$_COOKIE["color"];/*new color is blue*/?>
Deleting Cookie
==============================
<?php unset($_COOKIE["yourcookie"]);/*Or*/setcookie("yourcookie","yourvalue",time()-1);/*it expired so it's deleted*/?>
Reference: http://gencbilgin.net/php-cookie-kullanimi.html


A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.

Creating New Session
==========================
<?php
session_start
();/*session is started if you don't write this line can't use $_Session  global variable*/$_SESSION["newsession"]=$value;?>Getting Session
==========================
<?php
session_start
();/*session is started if you don't write this line can't use $_Session  global variable*/$_SESSION["newsession"]=$value;/*session created*/echo $_SESSION["newsession"];/*session was getting*/?>Updating Session
==========================
<?php
session_start
();/*session is started if you don't write this line can't use $_Session  global variable*/$_SESSION["newsession"]=$value;/*it is my new session*/$_SESSION["newsession"]=$updatedvalue;/*session updated*/?>Deleting Session
==========================
<?php
session_start
();/*session is started if you don't write this line can't use $_Session  global variable*/$_SESSION["newsession"]=$value;
unset(
$_SESSION["newsession"]);/*session deleted. if you try using this you've got an error*/?>
Reference: http://gencbilgin.net/php-session-kullanimi.html