Pass them along the chain. In the form for the login you'll need an extra input element to hold the referrer. You'll have to build the url and then encode it so that it doesn't affect the url it's being passed by.
<input type="hidden" name="referrer" value="<?php echo(urlencode($_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']));?>" />
HTH
Bubble