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

不打扰是莪最后的温柔 提交于 2019-12-17 05:38:01

问题


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" );


回答1:


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)



回答2:


Its so simple just use this

header("location:javascript://history.go(-1)");

Its working fine for me




回答3:


You have to save that location somehow.

Say it's a POST form, just put the current location in a hidden field and then use it in the header() Location.




回答4:


Just a little addition: I believe it's a common and known thing to add exit; after the header function in case we don't want the rest of the code to load or execute...

header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;



回答5:


Just try this in Javascript:

 $previous = "javascript:history.go(-1)";

Or you can try it in PHP:

if(isset($_SERVER['HTTP_REFERER'])) {
    $previous = $_SERVER['HTTP_REFERER'];
}



回答6:


Storing previous url in a session variable is bad, because the user might right click on multiple pages and then come back and save.

unless you save the previous url in the session variable to a hidden field in the form and after save header( "Location: save URL of calling page" );



来源:https://stackoverflow.com/questions/5285031/back-to-previous-page-with-header-location-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!