0

I want to know how to redirect user to particular link after login in php
for example in e-commerce website if user click on add to cart button and if that user is not logged in then user will be redirected to login page and after login user will be redirected to cart page which is requested page so,i want to know how to code for this.


if(!empty($_SESSION['username']))
{
        $url=' .php';//here i want dynamic link which is requested page link when user tries to access 
}
else
{
        $url='login.php';
}
Dipesh
  • 21
  • 6

5 Answers5

1

First check user is login or not

if(isset($_SESSION['username'])){
$url='cart.php';
}else{
$url='login.php';
}
<a href="<?php echo $url; ?>">add to cart</a>
Abhishek Sharma
  • 6,689
  • 1
  • 14
  • 20
0

You have to pass the variables for your reference to know from which page you are coming.

You have to use header() for this.

session_start();// beginning of your file.
if(user is logged in) {
     start checking for conditions here.
     if($_GET['from'] == "checkout"
          $file="checkout.php";
     else
          $file="index.php";

     header("Location: $file");// file to which you want to redirect after login.
} else {
     // redirect to login page.
}

You can pass from where you are coming to this page, then check that is user is logged in, then decide where to redirect.

Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41
0

Probably it would be quicker for you to Google this first than to take the time typing it into StackOverflow and waiting to monitor responses, but who's to say. Maybe your browser was already open on this page and you're using an old dialup modem so loading new non-cached content is very slow.

How to make a redirect in PHP?

Jameson
  • 6,400
  • 6
  • 32
  • 53
0

you can try this one:

header('Location: http://www.example.com/');

Here you can find useful links to free books:https://stackoverflow.com/tags/php/info

Community
  • 1
  • 1
Ivin Raj
  • 3,448
  • 2
  • 28
  • 65
0

login form

<form action="loginchk.php" method="post">
      <input type="text" name="unm" id="unm" />
      <input type="password" name="pwd" id="pwd" />
      <input type="hidden" name="redirect_url" value="<?php echo basename($_SERVER['PHP_SELF']); ?>" />
      <input type="submit" value="Login" />
</form>

loginchk.php

<?php 
    if(!empty($_POST)){
        extract($_POST);

        //sql query

        if(//true condition){
              header("location:".$redirect_url);
        } else{
              header("location:login.php");
        }
    }
?>
ImBhavin95
  • 1,494
  • 2
  • 16
  • 29