Well, you have to use the $SERVER['HTTP_REFERER'] element to find out where they were, or send the URL via a $GET item. Then store that either in the session or a hidden form field on the login form. Then when they log in, just redirect to the URL that they came from.
An example login form:
<?php
session_start();
$_SESSION['return_to'] = $_SERVER['HTTP_REFERER'];
?>
<form action="login.php">
<label for="username">Username:</label> <input type="text" name="username" id="username" /><br />
<label for="password">Password:</label> <input type="password" name="password" id="password" /><br />
<input type="submit" name="submit" value="Log In" />
<?php
echo ' <input type="hidden" name="return_to" value="' . $_SESSION['return_to'] . '" />';
?>
</form>
Then in your login...
<?php
session_start();
// do the authentication
if(/* login successful */)
header('Location: ' . $_SESSION['return_to']);
Hope that helps.