How sessions work in PHP

HTTP is a stateless protocol. Which means that every request the browser makes to the server cant be identified by the server as a subsequent request of that user/IP/browser or a brand new request.

HTTP doesn’t understand who is requesting. So how do sessions manage to make HTTP look intelligent? The Answer lies in the request-response model with data.


When a normal request is made, eg my website, the minimalistic data passed by the client/browser is this

GET / HTTP/1.1
Host: ruturaj.net

The server responds by giving the output. But when a developer does a session_start();, What actually happens is, the PHP engine sets a PHPSESSID cookie. This data is sent from the Server as Set-Cookie header. So the response goes somewhat like this

HTTP/1.x 200 OK
Date: xxxx
Set-Cookie: PHPSESSID=<32charhexvalue>; expires=xxxx
...

Now considering the browser does accept the cookies, it saves the PHPSESSID cookie. Consequently the server also creates a file in the specified directory (by default on Linux as /tmp) as /tmp/sess_32charid.

Now when another request is made by the user/browser, the Cookie header is passed through the GET request back to the server, something like this…

GET /session2.php HTTP/1.1
Host: ruturaj.net
Cookie: PHPSESSID=<32charid>; othercookies=othervalues;

The session2.php, for example, is setting a value of name in session, by this

$_SESSION['name'] = $name_obtained_from_somewhere;

Now as the script finishes, the script flushes all the $_SESSION data into the /tmp/sess_32charid file associated to that session id. It saves all the data in the serialized format

Consider the browser makes another request to session3.php where $_SESSION['name'] is echoed. Now when the request is made, just like previous case, the PHPSESSID is passed in the cookie.

Now as mandated by php.net, that every page where sessions should be needed, a session_start(); is required. So as soon this function is invoked, PHP checks if the browser’s request had any PHPSESSID cookie sent in the header, as it was sent in our case, PHP Engine will open /tmp/sess_32charid file (with the same session id) and unserialize the contents of the file. It then assigns the values of the unserialized data structures to the $_SESSION variable.

The simple echo $_SESSION['name']; will now be able to output the name!! Sessions working…

On a session_destroy();, PHP sends a destructive, previous timestamp cookie for PHPSESSID and unlinks or deletes the /tmp/sess_32charid file. This ensures that no reference of that session is left.

References

  • http://in3.php.net/manual/en/session.configuration.php

Automated MP3 tags updation with python

Had a wonderful song collection of Old hindi songs, in the format of “somenumber title (moviename).mp3”. Had to find way to update the ID3 tag info. Opensource to help yet again.

Installed a module named python-id3, Using yum install python-id3. Then wrote a small script in python using regular expressions, glob and the newly installed MP3 ID3 tagging module

#!/bin/env python

import os, glob, re, sys
from ID3 import *

def strip(str):
	return str.lstrip().rstrip()

os.chdir('/media/Carrington/Music/old-hindi-hit')
mp3s = glob.glob('*.mp3')

r = re.compile('([\d]+(([\s])*?[\w\s]+)\s?(\((.*?)\)?)?)\.mp3', re.I)

i = 1
for mp3 in mp3s:
	print str(i) + ": " + mp3
	gr = r.match(mp3)
	#print gr.groups()

	id3info = ID3(open(mp3, 'r+b'), mp3)
	title = ''
	album = ''
	try:
		if (len(gr.groups()) >= 4):
			print "Title: %s, Album: %s" % (strip(gr.group(2)), strip(gr.group(5)))
			title = strip(gr.group(2))
			album = strip(gr.group(5))
		else:
			print "Title: %s" % (strip(gr.group(2)))
			title = strip(gr.group(2))
		
		id3info.title = title
		id3info.album = album
		id3info.genre = 'Old Hindi'
		id3info.artist = ''
		id3info.write()
	except:
		print sys.exc_info()
	
	i = i + 1


Gmail style Static message box using jQuery

If u want to see a gmail style, “Loading” message box on ur application, its extremely simple using jQuery and CSS. All u need to know is

  1. jQuery
  2. HTML and good CSS, duh!

A ‘fixed’ element

First u need to have a fixed element, so u can define a div and give it css property as position: fixed;

jQuery methods to show, hide messages

U need to take a reference of the element, and then apply jQuery’s fadeIn and fadeOut method. A simple setTimeout can be set to automatically hide the message.

function notify(message, timeOut) {
	// Set the message using text method and chain fadeIn with it
	// apply simple setTimeout to fadeOut the message
	$('#boxd').text(message).fadeIn();
	setTimeout(function(){
		$('#boxd').fadeOut();
	}, timeOut*1000);
}

$(function(){
	// Wait to attach a event handler for the demo button
	$('#btn').click(function(){
		notify(new Date().toString(), 5);
	});
});

Check the attached example.

hands itching…

my hands are itching to write something, I don’t know what.. hmm.. Let me think. trek-a-log (i’ve been to none since long), life (I don’t really think much about it, sometimes)… perhaps something technical then..

Perhaps somebody reading this blog can suggest me, mail me @ ruturaj at gmail dot com

Kim Clijsters 2009 US Open Champion

Kim Clijsters was back with her best, becoming the first wild-carded entry winning the US Open against Caroline Wozniacki. It was a dream run for the young Dane, Caroline. Finally Kim’s experience was just too much. It ended 7-5, 6-3

Wozniacki Serves
Wozniacki Serves

Kim-backhand
Kim-backhand

Wozniacki misses
Wozniacki misses

Strong Clijsters
Strong Clijsters

Wozniacki gets some points
Wozniacki gets some points

Jada with her US Open champion mommy
Jada with her US Open champion mommy

Wozniacki still cheerful as a runner up
Wozniacki still cheerful as a runner up

Wozniacki still cheerful as a runner up
Wozniacki still cheerful as a runner up

Great comeback for Clijsters
Great comeback for Clijsters

Matheran Trip

18 Jul 09 was somehow destined to be a Matheran trip, whether Vj or Saurabh made it or not. Mukti was sure she would come, so was I. Luckily Paapad and Hemant (hempat) made it as well. Some snaps

Matheran Snaps Matheran Snaps Matheran Snaps
Matheran Snaps Matheran Snaps Matheran Snaps

Collage

Complete Gallery


Probably Mukti or Vinay could add a li’l travelogue for this one.

Geocities closing down

It was my first introduction to the HTML and web development, my first hosted page, http://www.geocities.com/ruturaj_v. Which over few years had become something like this

My geocities website

Unfortunately, today I got a mail from Yahoo saying that they just don’t love geocities anymore and would be knocking it off on 26 October 2009.

Geocities closing

As it goes down, It will take down numerous of other websites that had spawn on its platform, some of which just because they couldn’t bear the heavy costs before year 2000.

ऋतुराज का Home Page