Back to previous page with header( Location: ); in PHP
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)
Redirect back to previous page in PHP
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)");
How to redirect back to the previous page in PHP?
When the user is not login then the order page redirect the user to the login page first.
Why extra redirect?
Why not to show the login form right in place and upon successful login just redirect to the same page?
here is a brief example of the auth.php page
<?
if (isset($_POST['auth_name'])) {
$name = mysql_real_escape_string($_POST['auth_name']);
$pass = MD5($_POST['auth_name'].$_POST['auth_pass']);
$query = "SELECT * FROM users WHERE name='$name' AND pass='$pass'";
$res = mysql_query($query) or trigger_error(mysql_error().$query);
if ($row = mysql_fetch_assoc($res)) {
session_start();
$_SESSION['user_id'] = $row['id'];
}
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit;
}
if (isset($_GET['action']) AND $_GET['action']=="logout") {
session_start();
session_destroy();
header("Location: http://".$_SERVER['HTTP_HOST']."/");
exit;
}
if (isset($_REQUEST[session_name()])) session_start();
if (empty($_SESSION['user_id'])) {
return;
} else {
include 'top.php';
?>
<form method="POST">
<input type="text" name="auth_name"><br>
<input type="password" name="auth_pass"><br>
<input type="submit"><br>
</form>
<?
include 'bottom.php';
}
exit;
?>
now you can just use one following line to protect any page
require "auth.php";
Go Back to Previous Page
You can use a link to invoke history.go(-1)
in Javascript, which is essentially equivalent to clicking the Back button. Ideally, however, it'd be better to just create a link back to the URL from whence the user was posted to the form - that way the proper "flow" of history is preserved and the user doesn't wonder why they have something to click "Forward" to which is actually just submitting the form again.
Redirect back to previous page doesn't work as expected
Instead of HTTP_REFERRER
you can use location.reload()
after deleting a item to refresh the changed contents. Below is the example:
function deleteproduct(prod) {
if(confirm('Are you sure you want to delete this product')) {
$.get( "del_product.php", { act: "del",
masterCategory: "<?php echo $parent; ?>",
subCategory: "<?php echo $child; ?>",
productID: prodid } )
.done(function( data ) {
alert( "Data Loaded: " + data );
location.reload();
});
}
}
header location refering back to previous page with the last activated tab active
Add a hidden field to the form and put the hash in it. Then have your form processing script append the hash to the referer when constructing the redirect.
Another option is to put the current tab in a cookie, and select that tab whenever the page is opened.
Redirecting to previous page after login?
A common way to do this is to pass the user's current page to the Login form via a $_GET
variable.
For example: if you are reading an Article, and you want to leave a comment. The URL for comments is comment.php?articleid=17
. While comment.php
is loading, it notices that you are not logged in. It wants to send you to login.php
, like you showed earlier. However, we're going to change your script so that is also tells the login page to remember where you are:
header("Location:login.php?location=" . urlencode($_SERVER['REQUEST_URI']));
// Note: $_SERVER['REQUEST_URI'] is your current page
This should send the user to: login.php?location=comment.php%3Farticleid%3D17
. login.php
should now check to see if $_GET['location']
is populated. If it is populated, then send the user to this location (in this case, comment.php?articleid=17
). For example:
// login.php
echo '<input type="hidden" name="location" value="';
if(isset($_GET['location'])) {
echo htmlspecialchars($_GET['location']);
}
echo '" />';
// Will show something like this:
// <input type="hidden" name="location" value="comment.php?articleid=17" />
// login-check.php
session_start();
// our url is now stored as $_POST['location'] (posted from login.php). If it's blank, let's ignore it. Otherwise, let's do something with it.
$redirect = NULL;
if($_POST['location'] != '') {
$redirect = $_POST['location'];
}
if((empty($username) OR empty($password) AND !isset($_SESSION['id_login']))) {
$url = 'login.php?p=1';
// if we have a redirect URL, pass it back to login.php so we don't forget it
if(isset($redirect)) {
$url .= '&location=' . urlencode($redirect);
}
header("Location: " . $url);
exit();
}
elseif (!user_exists($username,$password) AND !isset($_SESSION['id_login'])) {
$url = 'login.php?p=2';
if(isset($redirect)) {
$url .= '&location=' . urlencode($redirect);
}
header("Location:" . $url);
exit();
}
elseif(isset($_SESSION['id_login'])) {
// if login is successful and there is a redirect address, send the user directly there
if($redirect) {
header("Location:". $redirect);
} else {
header("Location:login.php?p=3");
}
exit();
}
Gotchas
You should run some validation against $_GET['location']
before sending the user there. For example, if I tell people who use your site to click on this link: login.php?location=http%3A%2F%2Fmalice.com%2Fevilpage.php
... then they will be sent to a foreign URL that will try to do something bad.
Always make sure to use urlencode
when passing URLs as $_GET
parameters. This encodes special URL characters (such as ?
, &
, and %
) so that they don't break your url (e.g.: login.php?location=comment.php?id=17
<- this has two ?
's and will not work correctly)
Related Topics
Laravel: Validate an Integer Field That Needs to Be Greater Than Another
PHP Form Send Email to Multiple Recipients
PHP Random Shuffle Array Maintaining Key => Value
MySQL No Connection Could Be Made Because the Target MAChine Actively Refused It
PHP Function to Build Query String from Array
Symfony2 and Date_Default_Timezone_Get() - It Is Not Safe to Rely on the System's Timezone Settings
How to Read "Fetch(Pdo::Fetch_Assoc);"
Warning: MySQLi_Error() Expects Exactly 1 Parameter, 0 Given Error
How to Call a Model from a View
What Is a Unix Timestamp and Why Use It
How to Connect to Mssql Using Pdo Through PHP and Linux
How to Set the Env Variable for PHP
PHP Recursion to Get All Possibilities of Strings
MySQL Db Question Marks Instead of Hebrew Characters..
Laravel Recursive Relationships
Converting Object to JSON and JSON to Object in PHP, (Library Like Gson for Java)