Redirect back to previous page in PHP

55,373

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.

Share:
55,373
Admin
Author by

Admin

Updated on July 05, 2022

Comments

  • Admin
    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
    Funk Forty Niner almost 10 years
    HTTP_REFERER is not always reliable.
  • Ali Gajani
    Ali Gajani almost 10 years
    Has worked for me at least. Sessions another technique
  • Funk Forty Niner
    Funk Forty Niner almost 10 years
    Oh 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
    Ali Gajani almost 10 years
    I know, it's not the best method. Not good especially on HTTPS.
  • Funk Forty Niner
    Funk Forty Niner almost 10 years
    There 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
    Ali Gajani almost 10 years
    Will be glad to see it :) Patiently waiting
  • Funk Forty Niner
    Funk Forty Niner almost 10 years
    I 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
    Ali Gajani almost 10 years
    Thanks Fred, will look into this.
  • Ali Gajani
    Ali Gajani almost 10 years
    Sessions with Token would be a reliable form :)
  • Funk Forty Niner
    Funk Forty Niner almost 10 years
    Yes, totally. I've used such a method for a login script I made some time ago. Works beautifully.