The best method is to set a session variable (ie. PREVIOUS_REQUEST) on every request. This is the only sure method of retaining that information. This takes some work on your side, but atleast it's a sure bet.
The javascript history might be prohibited due to extreme security settings in the browser (ie. disabled javascript).
The $_SERVER['HTTP_REFERER']
value is also supplied by the browser, so this being filled is also not guaranteed.
$_SERVER['HTTP_REFERER']
could still be your best option, but do keep in mind its restrictions which you can find here:
In what cases will HTTP_REFERER be empty