I'm currently working on a mobile site with authentication using PHP sessions with a database.
I have a login page with a form that goes to server_login.php on submit. The php file then creates some session data (store in $_SESSION), and redirects the user back to the index page:
header("location:../../index.php");
The new web page (index.php) loads correctly; however, when the header redirects the page, the URL at the address bar is not changed; it stays at *http://localhost/php/server/server_login.php* instead of http://localhost/index.php and thus all my other resources that makes use of relative pathing could not be loaded. It's as if the web page still thinks that it resides at /php/server instead of /.
Strangely, my other use of header("location: ...") at logout.php works and redirects the page successfully with a URL change.
I've made sure that there are no outputs in my *server_login.php* before the header redirect (above it are just mysql calls to check) and I've used ob_start() and ob_end_flush() too.
Are there any methods of forcing the URL on the address bar to change (and thus hopefully fix the relative path problem)? Or am I doing something wrong?
P/S: I am using jQuery Mobile.
EDIT: Here's my code for the redirection that doesn't change the URL:
// some other stuff not shown
$sql = "SELECT * FROM $user_table WHERE email = '$myemail' AND password = '$mypassword'";
$login_result = mysql_query($sql, $connection);
$count = mysql_num_rows($login_result);
if ($count == 1) {
// Successfully verified login information
session_start();
if (!isset($_SESSION['is_logged_in'])) {
$_SESSION['is_logged_in'] = 1;
}
if (!isset($_SESSION['email'])) {
$_SESSION['email'] = $myemail;
}
if (!isset($_SESSION['password'])) {
$_SESSION['password'] = $mypassword;
}
// Register user's name and ID
if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id']))) {
$row = mysql_fetch_assoc($login_result);
$_SESSION['name'] = $row['name'];
$_SESSION['user_id'] = $row['user_id'];
}
header("Location: http://localhost:8080/meet2eat/index.php");
} else {
// Not logged in. Redirect back to login page
header("Location: http://localhost:8080/meet2eat/php/login.php?err=1");
}
Try changing:
header("Location : blabla")
^
|
(whitespace)
To
header("Location: blabla")
Well, if the server sends a correct redirection header, the browser redirects and therefore "changes the url". It might be a browser issue, then.
I don't know if it has anything to do with it, but you should not send a relative url in the location header ("HTTP/1.1 requires an absolute URI as argument to ยป Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. ", http://php.net/manual/en/function.header.php), and "location" must be capitalized, like:
header('Location: http://myhost.com/mypage.php');
In your form element add data-ajax="false". I had the same problem using jquery mobile.
Do not use any white space. I had the same issue. Then I removed white space like:
header("location:index.php"); or header('location:index.php');
Then it worked.
you may want to put a break; after your location:
header("HTTP/1.1 301 Moved Permanently");
header('Location: '. $YourArrayName["YourURL"] );
break;
I had the same problem with posting a form. What I did was that turning off the data-ajax.
Are you sure the page you are redirecting too doesn't have a redirection within that if no session data is found? That could be your problem
Also yes always add whitespace like #Peter O suggested.
I got a solution for you, Why dont you rather use Explode if your url is something like
Url-> website.com/test/blog.php
$StringExplo=explode("/",$_SERVER['REQUEST_URI']);
$HeadTo=$StringExplo[0]."/Index.php";
Header("Location: ".$HeadTo);
Just change home to your liking
$home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/home';
header('Location: ' . $home_url);
// Register user's name and ID
if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id']))) {
$row = mysql_fetch_assoc($login_result);
$_SESSION['name'] = $row['name'];
$_SESSION['user_id'] = $row['user_id'];
}
header("Location: http://localhost:8080/meet2eat/index.php");
change to
// Register user's name and ID
if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id']))) {
$row = mysql_fetch_assoc($login_result);
$_SESSION['name'] = $row['name'];
$_SESSION['user_id'] = $row['user_id'];
header("Location: http://localhost:8080/meet2eat/index.php");
}
As "cfphpflex" suggested you can add break; after setting the header. You can also echo something, such as echo 'test';.
Add exit at the end of header then it will work
header("location:index.php"); or header('location:index.php'); exit;
You are suppose to use it like header(Location:../index.php) if it in another folder
use
header("Location: index.php"); //this work in my site
read more on header() at php documentation.
why all of this location url?
http://localhost:8080/meet2eat/index.php
you can just use
index.php
if the php files are in the same folder and this is better because if you want to host the files
or change the port you will have no problem reaching this URL.
Related
After successful login, the user should be redirected to the page he came from, let's say he's been browsing a post and wants to log in so he can leave a comment, so he should be redirected to the post he was browsing. So here is what I have:
login.php shows the login form:
<form method="post" action="login-check.php">
... //input for username and password
</form>
The login-check.php checks if the username and pass are entered, does the user exist, or if he's already logged in, and a p parameter is sent to login.php:
<?php
session_start();
if((empty($username) OR empty($password) AND !isset($_SESSION['id_login']))) {
header("Location:login.php?p=1");
exit();
}
elseif (!user_exists($username,$password) AND !isset($_SESSION['id_login'])) {
header("Location:login.php?p=2");
exit();
}
elseif(isset($_SESSION['id_login'])) {
header("Location:login.php?p=3");
exit();
}
?>
then parameter p is sent back to login.php and displays the according message:
<?php
if(isset($_GET['p'])) {
$p = $_GET["p"];
if($p=="1")
echo "<p class=\"red\">You didn't fill the form.</p><br></br>";
if($p=="2")
echo "<p class=\"red\">User exists.</p><br></br>";
if($p=="3")
header("Location: index.php");
}
?>
BUT, instead of going to index.php after successful login, it should go to the page the user has previously been. I've tried in different ways, but it either doesn't work at all or returns to login.php.
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)
When user gets to the login page use this to see where is come from
$_SERVER['HTTP_REFERER']
Then set this value into the session, and when he is authenticated use url from the session to redirect him back. But you should do some checking before, if the url is your site. Maybe he come from another site directly to login :)
You can save a page using php, like this:
$_SESSION['current_page'] = $_SERVER['REQUEST_URI']
And return to the page with:
header("Location: ". $_SESSION['current_page'])
You should probably place the url to redirect to in a POST variable.
Since the login page is a separate page, I am assuming that you want to redirect to the page that the user reached the login page from.
$_SERVER['REQUEST_URI'] will simply hold the current page. What you want to do is use $_SERVER['HTTP_REFERER']
So save the HTTP_REFERER in a hidden element on your form <input type="hidden" name="referer" value="<?= $_SERVER['HTTP_REFERER'] ?>" /> but keep in mind that in the PHP that processes the form you will need some logic that redirects back to the login page if login fails but also to check that the referer is actually your website, if it isn't, then redirect back to the homepage.
Another way, using SESSION
Assign current URL to session (use it on every page)
$_SESSION['rdrurl'] = $_SERVER['REQUEST_URI'];
and in your login page, use
if(isset($_SESSION['rdrurl']))
header('location: '.$_SESSION['rdrurl']);
else
header('location: http://example.com');
use something like
$_SERVER['HTTP_REFERER'];
And if it's a successful login, display a link saying "Click here to go back" and a link to the referrer, and when the page loads, use some javascript to automatically load that page (don't use back() or whatever that function is as it won't re-load the page and it'll appear like the user never logged in.
You can use session to to store the current page on which you want to return after login and that will work for other pages if you maintain session properly. It is very useful technique as you can develop your breadcrumb using it.
you can use this:
$refererpage = $_SERVER['HTTP_REFERER']; //get referer stored in a variable
if (strpos($refererpage, $_SERVER['SERVER_NAME']) == TRUE) { //if the start position of the referer and the server name is equal
$refvar= $refererpage; //create a mew variable to be used to locate header
} else { //if referer's address is not the same as server name
$refvar= "index.php"; //set the variable to another direction for this request
}
and add the header where ever u want as:
header('location: '. $refvr); //set the header location to the referer varaible
You should try something like $_SERVER['HTTP_REFERER'].
You should first get user refer page in a variable using $_SERVER['HTTP_REFERER']; in your login page.
LIKE:
<?php
session_start();
$refPage = $_SERVER['HTTP_REFERER'];
?>
And now when the user clicks to Login then change header location to user refer page
LIKE:
<?php
if(isset($_POST[login])){
session_start();
header('location:' . $refPage);
}
?>
And in this time you should first check that user refers page empty or not because your user can visit direct your login page then your $refPage variable will be empty so after Click to Login page stays here
LIKE:
<?php
if(isset($_POST[login])){
session_start();
$refPage = $_SERVER['HTTP_REFERER']; // get reffer page url
if(empty($refPage)){
header('location: yourredirectpage'); // if ref page is empty then set default redirect page.
}else{
header('location:' . $refPage); // or if ref page in not empty then redirect page to reffer page
}
}
?>
Or you can use input type hidden where you can set value $_SERVER['HTTP_REFERER'];
LIKE:
<input type="hidden" name="refPage" value="<?php echo $_SERVER['HTTP_REFERER']; ?>">
And when a user clicks to Login then you can get the refPage value and redirect the previous page. And you should also check empty refer page. Because your user can visit direct your login page.
Thank you.
I have created a function to store URL of previous page
//functions.php
function set_previous_page_url(){
$current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$previous_url = $_SERVER['HTTP_REFERER'];
if (!($current_url === $previous_url)){
$_SESSION['redirect_url'] = $previous_url;
}
if(isset($_SESSION['redirect_url'])){
$url = $_SESSION['redirect_url'];
return $url;
} else {
$url = "index.php";
return $url;
}
}
And call this function in login.php
// login.php
<?php
// set previous page url to redirect after login
$url = set_previous_page_url();
if(ifItIsMethod('post')){
if(isset($_POST['username']) && isset($_POST['password'])){
if (login_user($_POST['username'], $_POST['password'])) {
redirect($url);
//unset session defined in set_previous_page_url() function
if(isset($_SESSION['redirect_url'])){
unset($_SESSION['redirect_url']);
}
}
}
}
?>
Construct the form action such that it 'remembers', or persists, the previous page by writing out a returnurl=value query string key/value pair to the URL - this can be passed from any page that redirects to login.
I think you might need the $_SERVER['REQUEST_URI'];
if(isset($_SESSION['id_login'])) {
header("Location:" . $_SERVER['REQUEST_URI']);
}
That should take the url they're at and redirect them them after a successful login.
how about this :: javascript+php
echo "<script language=javascript> javascript:history.back();</script>";
it will work same as the previous button in your browser
Use hidden input in your login page.
Like:
<input name="location" value="<?php if(!empty($_SERVER['HTTP_REFERER'])) echo $_SERVER['HTTP_REFERER']; else echo 'products.php'; ?>" type="text" style="display: none;" />
You can try
echo "<SCRIPT>alert(\"Login Successful Redirecting To Previous Page \");history.go(-2)</SCRIPT>";
Or
echo "<SCRIPT>alert(\"Login Successful Redirecting To Previous Page \");history.go(-1)</SCRIPT>";
#philipobenito's answer worked best for me.
I first created a hidden input that contain the user's HTTP referer
<input type="hidden" name="referer" value="<?= $_SERVER['HTTP_REFERER'] ?>" />
and after a successful login i redirected the users to whatever value was stored in that hidden input
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if(!empty($_POST['referer'])){
header('Location: '.$_POST['referer']);
}
else{
header('Location: members.php'); //members.php is a page used to send a user to their profile page.
}
exit;
I need a little help here. I have a page profile.php and a option to delete the accound :
// DELETE THE ACCOUNT !!
$_SESSION["delacc"] = FALSE;
if (isset ($_POST ['deleteaccount'])) {
$deleteaccount = $_POST['deleteaccount'];
$delacc="DELETE FROM users WHERE username='$username'";
$resdelacc = mysqli_query($con,$delacc);
if ($resdelacc) {
header('Location: index.php');
$_SESSION["delacc"] = TRUE;
unset($_SESSION['username']);
} else {
echo "ERROR !!! Something were wrong !!";
}
}
the problem is in if ($resdelacc). If this is true, result that the account was deleted, unset session username (logout) and after this I want to redirect the page to index.php where I have the code :
if(isset($_SESSION["delacc"])) {
if($_SESSION["delacc"] == TRUE) {
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
$_SESSION['delacc'] = FALSE;
}
}
My only problem is that this line " header('Location: index.php');" (from profile.php) don't run in any case. When the user click the button "DELETE ACCOUNT", the page remain profil.php, then, if do refresh or access another page, is redirected and appear as guest.
Very easy .. The reason is after in the resulted output page you can't redirect. so you've prepare it to be redirected after some seconds enough for user to read the result message.
Like this:
if($_SESSION["delacc"] == TRUE) {
$_SESSION['delacc'] = FALSE;
echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="7;url=http://'.$_SERVER['HTTP_HOST'].'/index.html"/>';
echo "</head><body>";
echo "<b><font color='red'>YOUR ACCOUNT WAS SUCCESFULLY DELETED !!</font></b>";
}
that change will redirect to the index.html after 7 seconds.
PS. The Generated HTML result page make it starts by this code after the POST handling direct. (before any echo) because echo will start generating the results page and the only logical place to redirect is inside the HEADER before any BODY elements
<meta http-equiv="refresh" content="0";url="/index.php"/>
The redirect (url) don't run for index.php because I have another redirect before :
if(isset($_SESSION['username'])==FALSE) {
header('Location: login.php');
}
but is ok, I put the message "DELETED SUCCESFULLY" in login.php and deleted from index.php . I set content=0, because after deleted, the user will be restricted for page profile.php and need to change immediatelly to another. Due of the verification of SESSION['username'] which can return profile.php, I can not redirect to another page ... is a conflict. I need a little to think better this code with redirects, I know can solve it better :D thanks for explanations and help
I'm trying to find a way to redirect a user to the page they selected if they have been forced to log in again after a session timeout.
Right now, after the user logs in, they are redirected to index.php. But, if a user received a link in an email to a different section of my site and they have not logged in all day, they are obviously asked to log in but end up on the index.php instead of the page the link was for.
Here is a snippet of my code in the login page:
if (mysql_num_rows($result_set) == 1) {
// username/password authenticated
// and only 1 match
$found_user = mysql_fetch_array($result_set);
$_SESSION['user_id'] = $found_user['id'];
$_SESSION['username'] = $found_user['username'];
$_SESSION['last_activity'] = time();
$_SESSION['time_out'] = 7200; // 2 hours
redirect_to("index.php");
Any ideas would be helpful.
I want to thank everyone who answered my question. The solution was a combination of a few suggestions I received here. I'd like to share with you how I solved this:
Part of the reason why I was having trouble saving the url the user tried to go to before being forced to log in again was that my sessions are handled by an external php file which takes care of confirming login and expiring current session. This file is required by all pages on my website. HTTP_REFERER would not work because it would always be set to the login.php. Here's what I did on my session.php file:
session_start();
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https')
=== FALSE ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['SCRIPT_NAME'];
$params = $_SERVER['QUERY_STRING'];
$currentUrl = $protocol . '://' . $host . $script . '?' . $params;
if ($currentUrl != "http://domain.com/login.php?") {
$expiryTime = time()+(60*5); // 5 mins
setcookie('referer',$currentUrl,$expiryTime,'/');
}
Essentially, I saved the referring url in a cookie that is set to expire in 5 minutes, giving the user enough time to login. Then, on login.php I did this:
if(isset($_COOKIE['referer'])) {
redirect_to($_COOKIE['referer']);
} else {
redirect_to('index.php');
}
And, BINGO! Works every time.
Try this:
$actual_link = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
if($actual_link == 'the email link'){
header('Location: '. $actual_link);
}else{
header('Location: index.php');
}
Try to save the URL in session whenever a user hit any url like http://www.abc.com/profile.php
once the user has successfully logged in redirect the user to saved URL(which is in session)
it the previous page is in the same directory and then you can try header('Location : .') or else if you if you need to redirect somewhere else.save the path before that situation occurs and in $url then u can redirect using header('Location: $url') or header('Location $url?values')
After successful login, the user should be redirected to the page he came from, let's say he's been browsing a post and wants to log in so he can leave a comment, so he should be redirected to the post he was browsing. So here is what I have:
login.php shows the login form:
<form method="post" action="login-check.php">
... //input for username and password
</form>
The login-check.php checks if the username and pass are entered, does the user exist, or if he's already logged in, and a p parameter is sent to login.php:
<?php
session_start();
if((empty($username) OR empty($password) AND !isset($_SESSION['id_login']))) {
header("Location:login.php?p=1");
exit();
}
elseif (!user_exists($username,$password) AND !isset($_SESSION['id_login'])) {
header("Location:login.php?p=2");
exit();
}
elseif(isset($_SESSION['id_login'])) {
header("Location:login.php?p=3");
exit();
}
?>
then parameter p is sent back to login.php and displays the according message:
<?php
if(isset($_GET['p'])) {
$p = $_GET["p"];
if($p=="1")
echo "<p class=\"red\">You didn't fill the form.</p><br></br>";
if($p=="2")
echo "<p class=\"red\">User exists.</p><br></br>";
if($p=="3")
header("Location: index.php");
}
?>
BUT, instead of going to index.php after successful login, it should go to the page the user has previously been. I've tried in different ways, but it either doesn't work at all or returns to login.php.
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)
When user gets to the login page use this to see where is come from
$_SERVER['HTTP_REFERER']
Then set this value into the session, and when he is authenticated use url from the session to redirect him back. But you should do some checking before, if the url is your site. Maybe he come from another site directly to login :)
You can save a page using php, like this:
$_SESSION['current_page'] = $_SERVER['REQUEST_URI']
And return to the page with:
header("Location: ". $_SESSION['current_page'])
You should probably place the url to redirect to in a POST variable.
Since the login page is a separate page, I am assuming that you want to redirect to the page that the user reached the login page from.
$_SERVER['REQUEST_URI'] will simply hold the current page. What you want to do is use $_SERVER['HTTP_REFERER']
So save the HTTP_REFERER in a hidden element on your form <input type="hidden" name="referer" value="<?= $_SERVER['HTTP_REFERER'] ?>" /> but keep in mind that in the PHP that processes the form you will need some logic that redirects back to the login page if login fails but also to check that the referer is actually your website, if it isn't, then redirect back to the homepage.
Another way, using SESSION
Assign current URL to session (use it on every page)
$_SESSION['rdrurl'] = $_SERVER['REQUEST_URI'];
and in your login page, use
if(isset($_SESSION['rdrurl']))
header('location: '.$_SESSION['rdrurl']);
else
header('location: http://example.com');
use something like
$_SERVER['HTTP_REFERER'];
And if it's a successful login, display a link saying "Click here to go back" and a link to the referrer, and when the page loads, use some javascript to automatically load that page (don't use back() or whatever that function is as it won't re-load the page and it'll appear like the user never logged in.
You can use session to to store the current page on which you want to return after login and that will work for other pages if you maintain session properly. It is very useful technique as you can develop your breadcrumb using it.
you can use this:
$refererpage = $_SERVER['HTTP_REFERER']; //get referer stored in a variable
if (strpos($refererpage, $_SERVER['SERVER_NAME']) == TRUE) { //if the start position of the referer and the server name is equal
$refvar= $refererpage; //create a mew variable to be used to locate header
} else { //if referer's address is not the same as server name
$refvar= "index.php"; //set the variable to another direction for this request
}
and add the header where ever u want as:
header('location: '. $refvr); //set the header location to the referer varaible
You should try something like $_SERVER['HTTP_REFERER'].
You should first get user refer page in a variable using $_SERVER['HTTP_REFERER']; in your login page.
LIKE:
<?php
session_start();
$refPage = $_SERVER['HTTP_REFERER'];
?>
And now when the user clicks to Login then change header location to user refer page
LIKE:
<?php
if(isset($_POST[login])){
session_start();
header('location:' . $refPage);
}
?>
And in this time you should first check that user refers page empty or not because your user can visit direct your login page then your $refPage variable will be empty so after Click to Login page stays here
LIKE:
<?php
if(isset($_POST[login])){
session_start();
$refPage = $_SERVER['HTTP_REFERER']; // get reffer page url
if(empty($refPage)){
header('location: yourredirectpage'); // if ref page is empty then set default redirect page.
}else{
header('location:' . $refPage); // or if ref page in not empty then redirect page to reffer page
}
}
?>
Or you can use input type hidden where you can set value $_SERVER['HTTP_REFERER'];
LIKE:
<input type="hidden" name="refPage" value="<?php echo $_SERVER['HTTP_REFERER']; ?>">
And when a user clicks to Login then you can get the refPage value and redirect the previous page. And you should also check empty refer page. Because your user can visit direct your login page.
Thank you.
I have created a function to store URL of previous page
//functions.php
function set_previous_page_url(){
$current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$previous_url = $_SERVER['HTTP_REFERER'];
if (!($current_url === $previous_url)){
$_SESSION['redirect_url'] = $previous_url;
}
if(isset($_SESSION['redirect_url'])){
$url = $_SESSION['redirect_url'];
return $url;
} else {
$url = "index.php";
return $url;
}
}
And call this function in login.php
// login.php
<?php
// set previous page url to redirect after login
$url = set_previous_page_url();
if(ifItIsMethod('post')){
if(isset($_POST['username']) && isset($_POST['password'])){
if (login_user($_POST['username'], $_POST['password'])) {
redirect($url);
//unset session defined in set_previous_page_url() function
if(isset($_SESSION['redirect_url'])){
unset($_SESSION['redirect_url']);
}
}
}
}
?>
Construct the form action such that it 'remembers', or persists, the previous page by writing out a returnurl=value query string key/value pair to the URL - this can be passed from any page that redirects to login.
I think you might need the $_SERVER['REQUEST_URI'];
if(isset($_SESSION['id_login'])) {
header("Location:" . $_SERVER['REQUEST_URI']);
}
That should take the url they're at and redirect them them after a successful login.
how about this :: javascript+php
echo "<script language=javascript> javascript:history.back();</script>";
it will work same as the previous button in your browser
Use hidden input in your login page.
Like:
<input name="location" value="<?php if(!empty($_SERVER['HTTP_REFERER'])) echo $_SERVER['HTTP_REFERER']; else echo 'products.php'; ?>" type="text" style="display: none;" />
You can try
echo "<SCRIPT>alert(\"Login Successful Redirecting To Previous Page \");history.go(-2)</SCRIPT>";
Or
echo "<SCRIPT>alert(\"Login Successful Redirecting To Previous Page \");history.go(-1)</SCRIPT>";
#philipobenito's answer worked best for me.
I first created a hidden input that contain the user's HTTP referer
<input type="hidden" name="referer" value="<?= $_SERVER['HTTP_REFERER'] ?>" />
and after a successful login i redirected the users to whatever value was stored in that hidden input
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if(!empty($_POST['referer'])){
header('Location: '.$_POST['referer']);
}
else{
header('Location: members.php'); //members.php is a page used to send a user to their profile page.
}
exit;
It works when I input
header("Location: http://www.google.com");
but it doesn't work when I have
header("Location: $_SERVER['HTTP_REFERER']");
I want to redirect the page to whatever page it came from.
Try it: :)
if (!empty($_SERVER['HTTP_REFERER']))
header("Location: ".$_SERVER['HTTP_REFERER']);
else
echo "No referrer.";
However, for determining which page user came from, I'd rather use session variable, which gets reset at every page:
session_start();
echo "Previous page:", $_SESSION['loc'];
$_SESSION['loc']=$_SERVER['PHP_SELF'];
ps: This only works for local pages, you cannot track other websites.
You might try:
header("Location: {$_SERVER['HTTP_REFERER']}");
I've had problems with variable expressions which contain quotes in strings without braces.
You also need to look out for $_SERVER['HTTP_REFERER'] simply not being set. Some user agents don't set it, some privary tools mask it, and you need to handle people coming to your page without a referrer.
Here is a simple solution.
check and see what $_server['http_referer'] is giving you and if its set then you can redirect and if not put a fall back url something like :
if(isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] != ""){
$url = $_SERVER['HTTP_REFERER'];
}else{
$url = "YOUR INDEX PAGE OR SOMETHING";
}
header("Location: ".$url);
This is a browser feature, and any polite browser will send the
correct header (although various 'security' tools will override this
with a fake referer).
It's browser specific so not every browser/security software combination will send it to the server. You're better off setting a session variable on each page load to determine which page the user came from (or something similar with a bit more logic)
header("Location: $_SERVER[HTTP_REFERER]");
Without the single quotes. This is the fastest way to access and concatenate array values without extra concatenating code.
Simply you can use
if(isset($_SERVER['HTTP_REFERER'])){
header("Location:".$_SERVER['HTTP_REFERER']."");
}
One of the mistakes that occure sometimes is, that NO OUTPUT must happen before header('Location: ' ....)
This is not working (shows the output, but doesn't redirect):
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
$cleaned_url = preg_replace('/[^a-z ]+/i', '', strtolower($referer));
$pattern = '/troester/';
$res = preg_match($pattern, $cleaned_url);
echo $res; // <--- OUTPUT COMES HERE
if ($res == true) header("Location: {$referer}");
}
This is working (does redirect properly):
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
$cleaned_url = preg_replace('/[^a-z ]+/i', '', strtolower($referer));
$pattern = '/troester/';
$res = preg_match($pattern, $cleaned_url);
//echo $res; // <--- NO OUTPUT COMES HERE
if ($res == true) header("Location: {$referer}");
}
This is also working, but doesn't make sense ():
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
$cleaned_url = preg_replace('/[^a-z ]+/i', '', strtolower($referer));
$pattern = '/troester/';
$res = preg_match($pattern, $cleaned_url);
if ($res == true) header("Location: {$referer}");
echo $res; // <--- OUTPUT COMES HERE, AFTER header('Location: ' ....)
}
(For better understandig, hope this may help)