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:
Then page B has the original url sent by page A. I often use this technique and it's very reliable.
<input type="hidden" name="redirect" value="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']) ?>" />
If you don't use forms then you can pass the original url from A to B in the link as a parameter:
$link_to_B = 'pageB.php?redirect=' . urlencode($_SERVER['REQUEST_URI']);