Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to go to the same page after login in PHP

For example,

STEP 1:

I am browsing a page without logging in and my last page before logging in is beforeLogin.php

STEP 2:

Now my prob is when i logged in i am redirecting to the index.php page. Instead i should be redirected to the last page what i had browsed.

That is from the above example is should redirected to beforeLogin.php

How should this can be done.

Any help will be appreciable.

thanks in advance

like image 845
Fero Avatar asked Mar 28 '10 06:03

Fero


People also ask

How to redirect to same page in php after submit?

You should redirect with a location header after every post, because otherwise when the user presses the refresh button, it will send again the same form... Btw. if you want to do proper work, you should try out a php framework instead of this kind of spaghetti code...

How to redirect user after login in php?

if ($count == 1){ $_SESSION['username'] = $username; header("location:redirectafterlogin. php"); //header to redirect, but doesnt work }else{ //3.1. 3 If the login credentials doesn't match, he will be shown with an error message.

How do I redirect a page after login?

The most common ways to implement redirection logic after login are: using HTTP Referer header. saving the original request in the session. appending original URL to the redirected login URL.

How to redirect to login page in php?

Answer: Use the PHP header() Function You can simply use the PHP header() function to redirect a user to a different page. The PHP code in the following example will redirect the user from the page in which it is placed to the URL http://www.example.com/another-page.php .


1 Answers

You would need a way to keep track of the web pages visited, so you can back-reference to the last page the user has browsed to.

When I think of tracking a user's session across multiple-pages I, like every other PHP programmer, think of using sessions.

A possible way could be to store the link visited into a session variable and then when the user reaches the login.php page (the page to login into) provide a header redirect to $url given by the session variable.

NOTE: Below code snippets, have not been tested or compiled.

You can paste this code into all your pages on your website:

<?php
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI']; // i.e. "about.php"

This utilizes the $_SERVER variables to return the URI of the current page visited using $_SERVER['REQUEST_URI']

And then for the login page to help further demonstrate:

<?php
session_start();  // needed for sessions.
if(isset($_SESSION['url'])) 
   $url = $_SESSION['url']; // holds url for last page visited.
else 
   $url = "index.php"; // default page for 

header("Location: http://example.com/$url"); // perform correct redirect.
like image 190
Anthony Forloney Avatar answered Sep 25 '22 10:09

Anthony Forloney