If the user goes from A to B by submitting a form then you can do it easily by submitting the url of A in a hidden element:
HTML Code:
<input type="hidden" name="redirect" value="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']) ?>" />
Then page B has the original url sent by page A. I often use this technique and it's very reliable.
If you don't use forms then you can pass the original url from A to B in the link as a parameter:
PHP Code:
$link_to_B = 'pageB.php?redirect=' . urlencode($_SERVER['REQUEST_URI']);
You could also use cookies or sessions to store the url of A but then this won't work properly when someone has two tabs/windows open at the same time and go through these pages concurrently.
Bookmarks