PASTE NAVIGATION MENU CODE

Saturday 14 April 2012

PHP Sessions & Cookies

| | with 0 comments |
As discussed in previous posts, PHP is a very popular, open-source and efficient server-side scripting language. It is envisaged that PHP will also be used in the development of The Ball Game which will be part of this blog.

In this post, we discuss PHP sessions and cookies, two integral parts of any PHP applications.

Sessions
When browsing a web page, a web browser will start a "session". This session is a saved state, lasting till the user closes their browser or until the server-side language explicitly destroys it.

Figure: PHP Session

As we can see from the image above, HTTP is an inherently stateless protocol. It simply delivers requests from the web client to the web server, and responses from the web server to the client. Hence, it is up to the server-side scripting language (from now on simply referred to as PHP) to maintain session information, in collaboration with the web client.

As can be seen from the diagram above, sessions are used to store a user's login. Were this not the case, the user would have to login every time they navigate from one page of a site to another. When the user logs in, the server generates a session identifier, which uniquely identifies that user. This session ID is stored by PHP once the authentication credentials provided by the client are validated. When navigating to further pages, PHP will check the session id to ensure the client is a valid one, and will show secure content without requiring authentication.

As can also be seen, sessions can be set to expire. Normally, sessions expire for one of three reasons.
  • The client closes their browser window.
  • The session is set to expire after a certain amount of time of inactivity.
  • The client explicitly logs out, and hence the session is destroyed.
 When this happens, the client has to login again in order to gain access to secure content.

Cookies
As mentioned previously, sessions expire when the browser window is closed. Cookies are a way for sessions to persist even when the browser is reopened.

Figure: PHP Cookie

In the above scenario, information is being stored inside the session. However, that session is also being stored inside a cookie. A cookie is information which is stored inside a file on the users computer. When reopening the browser and navigating to a site, the site will ask the browser for related cookies. The session id in the cookie is then read and, if not expired, the session can resume.

Cookies are normally set to expire after a few days, however they can also be set to never expire (or expire in the very far future). This way, the user will be permanently logged into the site. For example, popular sites such as Gmail always store the user session id, meaning the user's inbox is instantly loaded whenever visiting gmail.com. Moreover, Google has also merged all their sites into a single logging system, so logging into Gmail will also log you into all of Google's other services.

Storing cookies on a users computer could pose a security risk. Firstly, someone other than the user may be using the computer, and will simply open up a browser and find themselves logged in to someone else's account (especially on a public computer). Normally, sites will ask for a password when changing account settings on purchasing services, as an added security measure.

Additional threats come from spyware, which can use the cookies to browse sites on behalf of the user and collect information. Despite their threats, it is good to have cookies enabled as long as the computer has relevant security measures, as these can greatly improve the browsing experience.

Sessions in PHP
Using sessions in PHP is very easy.

<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>

In the above code, we see how a session is first started using the PHP session_start() function. This must be called from every PHP page in the web application which is making use of sessions. Once called, the $_SESSION superglobal array becomes available, within which the programmer can store session information.

In the case of the code above, a 'views' key is created in the $_SESSION array, storing the number of views the site has had. This is then shown on the page. The code first checks whether the session variable has been set, and if so increments the views. If not, the views are set to 1.

Since this is a session variable, closing the browser and then reopening it will result in the view counter being reset to 1.

If the user logs out, or we need to remove the session data for whatever reason, we can use

unset($_SESSION['views']);

followed by

session_destroy();

The first will remove a particular session variable, whilst the second one will completely destroy the session.

Cookies in PHP
Cookies are set in PHP using the setcookie() function. For example

setcookie(name, value, expire, path, domain, secure, httponly);

The code above shows the parameters accepted by the function:
  • name - the name of the value being stored in the cookie.
  • value - the value associated with the name above.
  • expire - the time when the cookie expires.
  • path - the location to store the cookie in.
  • domain - the domain (and sub-domain) the cookie is available to
  • secure - a boolean value specifying the cookie should be transmitted over an HTTPS connection.
  • httponly - a boolean value specifying the cookie can only be sent over HTTP(S). 
Of the above parameters, only the name parameter is required. 

setcookie("user", "Lucy Smith", time()+3600);

In the above listing, we are saving a cookie value "user" with the value "Lucy Smith". The time()+3600 argument means "the current time plus 3600 seconds", which means this cookie will expire after an hour. Once the cookie has been set, the value can be accessed from the $_COOKIE superglobal array.

echo $_COOKIE["user"];

Which will display "Lucy Smith". 

To delete the cookie, we simply make the cookie expire.

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

The above makes the cookie expire one hour ago, meaning it will be deleted by the browser.



Source:

Harvard Extension School 2011 - CSCI E-12 Fundamentals of Website Design
Link: Click Here

Post a Comment

Please enter your comments here..

0 comments: