Fero Fero - 7 months ago 20
PHP Question

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

Answer

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.