Jump to content

Redirect To previous page


YNWA

Recommended Posts

Heres the situation. Currently using WAMP to design my PHP website for University.

 

I have my code working. I have Login, Add Book, Edit Book, Delete Book, Register, Logout and they all work.

 

However to add/edit/delete a book you need to be logged in. The form woks if you are already logged in but if your not, you will see two links, one for login page and one for register.

 

How do I allow a user to click the login link, login and then have them automatically returned to the page they clicked the link from?

 

Say I go to add book, cant so click login, then once logged in I get my message 'logged in' and the page then goes to add book page automatically for user to then add a book?

 

What code and were within my PHP file should I put it?

 

Cheers in advance

Link to comment
Share on other sites

I imagine you're using sessions to track whether or not they're logged in.  So you'd want to do something like this.

 

<?php
// 1. If they're not logged in save the location.  This code is to be ran at the top of every page in the site
if(!isset($_SESSION['uid'])){ // Assuming the user id is saved as 'uid' otherwise specify whatever session field you're saving
$_SESSION['redirect'] = $_SERVER['REQUEST_URI'];
header("Location: login.php");
}

// 2. This code should be on the login page, following the validation of the user.  If they login successfully run the following code
if(isset($_SESSION['redirect'])){
  $location = $_SESSION['redirect']; // If they tried going to a secure page, redirect to page they tried to view
}else{
  $location = "home.php"; // If they didn't redirect them to homepage as a logged in user
}
header("Location: $location");
?>

 

This is a basic example but it should get you started.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.