PHP

Tracking session data

1. Hidden form fields

Example Basic HTML:

<form action="ServerActionName" method="post"><input type="hidden" value="hidden value let's say yellow" name="color" />
</form>

The pro is that it is simple and works for simple cases.

The con is that everypage must have a form that has a hidden input field in order to move the session data to the next page.

2. Url rewriting

A way to store url params and rewrite them to the next pages
Example PHP:

let’s say we arrived from a url: www.somename.com/home.php?guestNum=987654 and we want to rewrite the url params to the next page.

<?php
 if (isset($_GET['guestNum'])) {
   $guestNum= $_GET['guestNum'];
   <a href="http://somename.com/guestPage.php?newParam=hello&guestNum="  
   + $guestNum>Click Here </a> 
 }

 else { // Fallback behaviour } 

?>

The pro is that it is simple and works for simple cases.

The con is that the referal element must concat to its’ url’s new query string every parameter that was gathered before in order to move the session data to the next page.

3. Cookies

Example C# – retrieving a cookie if exists and if not storing it for the next pages:

var request = HttpContext.Current.Request;

if (request.Cookies["Age"] != null)
{
    string Age=  Request.Cookies["Age"];
}
else
{
var response = HttpContext.Current.Response;
HttpCookie myCookie = new HttpCookie("someCookieName");
//some logic probably here...
//20 is just hardcoded for the example
myCookie["Age"] = "20";
myCookie.Expires = DateTime.Now.AddDays(1d);
response.Cookies.Add(myCookie);
}

The pro is that the cookies allow the data to be stored on the user’s side.

The cons are 1-that the cookies are stored per browser and won’t be available on other browsers( which will recieve each their own cookies), and 2- only strings can be stored in cookies.

4. Session Data

Java Example:
On a servlet page

HttpSession session = request.getSession();
session.setAttribute("user", "Yair");

Then on another servlet page retrieve the session attribute

String user = null;
if(session.getAttribute("user") == null){
	response.sendRedirect("login.html");
}else user = (String) session.getAttribute("user");

The pro is that it maintains user information securely on server side(object and strings) and only stores sessionId string in a user’s cookie.

The con is that because the session and its object data are allocated server memory they shouldn’t be set indefinetly because they can clot up after a while.