I'll leave the code part to the pro's for I am not sure about this.
But what I can tell you, is that there is a library for doing this... Pitty, I can't remeber the name. But there was (I remeber it in... phpNuke, I suppose).
So you could try searching Google for something like this instead of writing you own.