redirect to the current page after login

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mittul
Forum Newbie
Posts: 4
Joined: Tue Jul 26, 2011 4:27 am

redirect to the current page after login

Post 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 ./. .
Last edited by Benjamin on Tue Jul 26, 2011 5:11 am, edited 1 time in total.
Reason: Added [syntax=php|sql|css|javascript] and/or [text] tags.
xtiano77
Forum Commoner
Posts: 72
Joined: Tue Sep 22, 2009 10:53 am
Location: Texas

Re: redirect to the current page after login

Post 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!
Post Reply