Thursday, September 2, 2010

Sessions and Cookies in PHP

PHP Cookies :

  • A message given to a Web browser by a Web server. The browser stores the message in a text file. The message is then sent back to the server each time the browser requests a page from the server.
  • A cookie is often used to identify a user

What is a Cookie?
  • A cookie is often used to identify a user. 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.

How to Create a Cookie?

The setcookie() function is used to set a cookie.

Note:The setcookie() function must appear BEFORE the tag.

Syntax:
setcookie(name, value, expire, path, domain);



Set Cookies:- 
setcookie("user","tom",time()+3660);
echo "cookie is set";

Retrieve Cookies:-
echo "Cookie value is ".$_COOKIE['user'];


Note: The value of the cookie is automatically URL encoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use set raw cookie() instead).



How to Retrieve a Cookie Value?
The PHP $_COOKIE variable is used to retrieve a cookie value.

In the example below, we retrieve the value of the cookie named "user" and display it on a page:

Example :
echo $_COOKIE["user"];

In the following example we use the isset() function to find out if a cookie has been set:
Example:
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!";
else
echo "Welcome guest!";



How to Delete a Cookie?
When deleting a cookie you should assure that the expiration date is in the past.

Example:
setcookie("user", "", time()-3600);




PHP Sessions:
  • A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.


PHP Session Variables

  • When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
  • A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
  • Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
  • A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping cart items, etc). However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions. 
  • It is important to ponder if the sessions' temporary storage is applicable to your website. If you require a more permanent storage you will need to find another solution, like a MySQL database.
  • Sessions work by creating a unique identification (UID) number for each visitor and storing variables based on this ID. This helps to prevent two users' data from getting confused with one another when visiting the same webpage.

    Note: If you are not experienced with session programming it is not recommended that you use sessions on a website that requires high-security, as there are security holes that take some advanced techniques to plug. 
Starting a PHP Session
  • Before you can begin storing user information in your PHP session, you must first start the session. When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.







This tiny piece of code will register the user's session with the server, allow you to start saving user information and assign a UID (unique identification number) for that user's session.

Storing a Session Variable :
  • The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
Example:
session_start();
$_SESSION['views']=1; //Storing value in session variable.
echo "Pageviews=". $_SESSION['views']; //Retriving the value of session variable.

Destroying a Session :
  • If you wish to delete some session data, you can use the unset()or the session_destroy() function.
  • The unset() function is used to free the specified session variable.
Example:
unset($_SESSION['views']);

You can also completely destroy the session by calling the session_destroy() function.
session_destroy();
Note:session_destroy() will reset your session and you will lose all your stored session data.


Understanding session
  • This piece of code does one of two things. If the user does not already have a session, it creates a new session -or -if the user does already have a session it connects to the existing session file. When a new session is created, PHP session management generates a session identifier that consists of a random 32 hex digit string and creates an empty session file on the server with the  name sess_ followed by the session identifier. It also includes a set-cookie in the response and a session cookie in the browser with the value of the session identifier. This means that any subsequent request to the server will include this session identifier allowing PHP to connect to the appropriate session file.
  • session_start();

No comments:

Post a Comment