单击链接时强制用户登录

时间:2013-05-27 08:36:02

标签: php redirect login

我有这个代码,我用它来发送用户电子邮件的批准。 我需要的是:当用户点击链接时;他应该首先登录,然后他可以进行审批流程。 我尝试了以下代码来检查会话是否未注册,然后强制用户登录(index.php):

global $user_ID;
$user_ID = $_SESSION['empName'];
if ($user_ID == '') { 
header('Location: index.php'); exit(); 
} 
echo "<INPUT type='hidden' name='Code' size = '6' value ='hr1.php' />";
if(isset($_POST['Code'])){$Code = $_POST['Code'];}
mysql_close($con);

现在我需要一种方法将用户重定向到上一页(链接)

任何想法???

4 个答案:

答案 0 :(得分:1)

在重定向到登录页面时,然后存储名为return_url

的会话值
$_SESSION['return_url'] = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

然后,如果登录成功,则检查return_url是否存在。如果存在,则返回$_SESSION['return_url']

header("Location: ".$_SESSION['return_url']);

答案 1 :(得分:0)

为什么当他点击链接并且没有登录时,不会将您当前的网址发送为parameter

我的意思是,您必须添加JS,例如,当您点击该链接时,将parameter添加到您的网址:?lastUrl=/foo/foo.com

然后,将url保存到变量中,检查用户是否登录并返回变量(last url)。

JS建议:

没有jQuery

window.onload = function() {
    var element = document.getElementById('checkLogin');
    element.setAttribute('src') = element.getAttribute('src') + '?' + 
        window.location.href;
}   // or you can add it into onclick method of your link,
    // but I think this is easier.

答案 2 :(得分:0)

只需为授权制作,并在每个页面上包含此文件。

auth.php

<?php
session_start(); //remove this if you do this somewhere else
if (empty($_SESSION['empName']) && !isset($_SESSION['empName'])) {  
header('Location: index.php'); exit(); 
}

page.php文件

<?php
include 'auth.php';
echo "<INPUT type='hidden' name='Code' size = '6' value ='hr1.php' />";
if(isset($_POST['Code'])){$Code = $_POST['Code'];}
mysql_close($con);

答案 3 :(得分:0)

您可以在将用户重定向到登录页面之前将当前页面保存到会话:$_SESSION['current_url'] = get_current_url()。请参阅get_current_url() here

登录后,您只需将用户重定向到上一页:

if(isset($_SESSION['current_url'])) {
  header("Location: ".$_SESSION['current_url']);
} else {
  header("Location: index.php");
}