Back to previous page with header( "Location: " ); in PHP

Web_Designer picture Web_Designer · Mar 12, 2011 · Viewed 397.1k times · Source

The title of this question kind of explains my question. How do I redirect the PHP page visitor back to their previous page with the header( "Location: URL of previous page" );

Answer

Dimitry picture Dimitry · Mar 12, 2011

try:

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, sending the user to some other destination. The header may not even be sent by the browser.

Ideally, you will want to either:

  • Append the return address to the request as a query variable (eg. ?back=/list)
  • Define a return page in your code (ie. all successful form submissions redirect to the listing page)
  • Provide the user the option of where they want to go next (eg. Save and continue editing or just Save)