Page 1 of 1

redirect to the current page after login

Posted: Tue Jul 26, 2011 4:50 am
by mittul
well .. i m using SESSIONS in my login , logout , profile and other pages .. the code looks like this for my session creation when the user loggs in . .

---------------------------------------------
login.php (not full code .. just showing my session creation here)
-----------------

Code: Select all

if(mysql_num_rows($result) == 1)
		{		
			$name = $_POST['name'];
			$_SESSION['myusername'] = $name;
			header("Location:profile.php");
			echo 'correct';
		}
---------------------------------------------

---------------------------------------------
profile.php
-----------------

Code: Select all

<?php
session_start();
if(!isset($_SESSION['myusername'] ))
{
	header('Location:login.php');
}
---------------------------------------------


and i have used session_destroy() in my logout.php page ..

but my question comes here .. suppose i have other pages and if the user is not logged in and he/she wants to see that page then he/she will be automatically redirected to the login page .. and as soon as he/she logs in then he/she will automatically be logged in to the particular page which he/she wants to see b4 .. how can i do this ..

here m just redirecting the users go to PROFILE.PHP .. but what should i do if i have " anotherpage.php " for example to do which i told you ..

please help me . .

thank you ./. .

Re: redirect to the current page after login

Posted: Sun Jul 31, 2011 10:27 pm
by xtiano77
This may be a little simplistic, but I would try the following:

Code: Select all

if(mysql_num_rows($result) == 1){
     $name = $_POST['name'];
     $_SESSION['myusername'] = $name;
     if(isset($_SESSION["RETURN_TO_PAGE"])){
          header("Location: http://www.yourwebsite.com" . $_SESSION["RETURN_TO_PAGE"]);
     }else{
          header("Location:profile.php");
          echo 'correct';
     }
}
Requested page:

Code: Select all

<?php
session_start();
if(!isset($_SESSION['myusername'] )){
     $_SESSION["RETURN_TO_PAGE"] = $_SERVER["PHP_SELF"];
     header('Location:login.php');
}
# rest of your code here...
Just my two cents!