This is a pretty broad subject, so I suggest a little reading might help. Here is an old Lincoln Stein TPJ article to get you started. Note that although Lincoln uses mod_perl for implementation, the techniques he discribes can easily be applied other ways.
in reply to Implementing Cookies
Once you have good understanding of technique checkout Apache::Session.
mitd-Made in the Dark
'Interactive! Paper tape is interactive!
If you don't believe me I can show
you my paper cut scars!'
Edited by footpad, ~Tue Nov 20 05:44:12 2001 UTC: Fixed broken HTML