Redirect back to previous page in PHP
Solution 1
try this
header('Location: ' . $_SERVER['HTTP_REFERER']);
Note that this may not work with secure pages (HTTPS) and it's a pretty bad idea overall as the header can be hijacked.
or
header("location:javascript://history.go(-1)");
Solution 2
Try this: header('Location: ' . $_SERVER['HTTP_REFERER']);
'HTTP_REFERER'
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
Admin
Updated on July 05, 2022Comments
-
Admin almost 2 years
How do I redirect to a previous page using
header("Location:...")
? The problem occurs when a user is scrolling down in a page to find a link for example, then clicks it - opens another page, clicks the link I've given "Go back to links (header("Location:links.php");
)", but when the user clicks it, it will head to previous page but on the top part of the page.The user must scroll down again where he found the link he just clicked (which is frustrating). Is there a php code like the 'back'-button used in web browsers where you will go back to the exact location and page right before you click something else?
-
Funk Forty Niner almost 10 years
HTTP_REFERER
is not always reliable. -
Ali Gajani almost 10 yearsHas worked for me at least. Sessions another technique
-
Funk Forty Niner almost 10 yearsOh it works, in many circumstances, but it's not always reliable. I would have to find the related pages for that, but I don't have time right now to Google this. But from memory, it's not the best method to use; just saying.
-
Ali Gajani almost 10 yearsI know, it's not the best method. Not good especially on HTTPS.
-
Funk Forty Niner almost 10 yearsThere was a page/question on SO about a month or so ago, where they had discussed a similar issue, and someone had devised a genius way for doing this, and for the life of me, I never did find it again. It may very well be inside one of my favorites, but that could take a while lol
-
Ali Gajani almost 10 yearsWill be glad to see it :) Patiently waiting
-
Funk Forty Niner almost 10 yearsI found this as to why using
HTTP_REFERER
is not reliable: => stackoverflow.com/a/5934792 and I think I may have found that method using sessions stackoverflow.com/a/13703882 -
Ali Gajani almost 10 yearsThanks Fred, will look into this.
-
Ali Gajani almost 10 yearsSessions with Token would be a reliable form :)
-
Funk Forty Niner almost 10 yearsYes, totally. I've used such a method for a login script I made some time ago. Works beautifully.