It seems that there is lots of repetition in this code. Could you minimize/dehydrate it somehow. It seems that the only thing which changes if the if statement is the last part of the Location header.

You could probably do something like this:
$location = (if cond) ? a : b;
header('Location: ' . ..... . $location);
unset(....);