简体   繁体   English

在PHP中登录后如何将用户重定向到特定链接

[英]how to redirect user to particular link after login in php

I want to know how to redirect user to particular link after login in php 我想知道如何在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';
}

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>

You have to pass the variables for your reference to know from which page you are coming. 您必须传递变量以供参考,以了解您来自哪个页面。

You have to use header() for this. 您必须为此使用header()

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. 您可以从您要访问的页面进入该页面,然后检查用户是否已登录,然后确定重定向到的位置。

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. 首先,您可能比花时间在StackOverflow中键入它并等待监视响应要快得多,但是对于谁说呢。 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? 如何在PHP中进行重定向?

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 在这里,您可以找到免费书籍的有用链接: https : //stackoverflow.com/tags/php/info

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 loginchk.php

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

        //sql query

        if(//true condition){
              header("location:".$redirect_url);
        } else{
              header("location:login.php");
        }
    }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM