If the login page is generated by the link they clicked, the url by which they accessed the login page will be the url you want to redirect them to after login, so you can add e.g. an extra hidden form element that contains this data to the login page -
<input type="hidden" name="redirect_dest" value="http://<?php print($_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']); ?>" />
If the link they clicked redirects them to a login page, the path you want to redirect them back to is probably in $_SERVER['HTTP_REFERER'], so you could put this in your (e.g.) extra form element.