Php 使用Ajax和标头重定向注销错误
我试图做一些事情,如果用户在未登录时尝试在我的系统中执行功能,它将弹出一条消息,说他们无法执行,因为他们未登录。当他们按下ok时,他们会被发送到登录屏幕 如果用户直接键入url,我还希望它将用户重定向回登录屏幕,但这次没有错误消息 我有:Php 使用Ajax和标头重定向注销错误,php,ajax,security,login,http-headers,Php,Ajax,Security,Login,Http Headers,我试图做一些事情,如果用户在未登录时尝试在我的系统中执行功能,它将弹出一条消息,说他们无法执行,因为他们未登录。当他们按下ok时,他们会被发送到登录屏幕 如果用户直接键入url,我还希望它将用户重定向回登录屏幕,但这次没有错误消息 我有: $components = explode('/', $url, 3) ; if(!isset($_SESSION['loggedin']) && $components[0] != 'access' && $componen
$components = explode('/', $url, 3) ;
if(!isset($_SESSION['loggedin']) && $components[0] != 'access' && $components[0] != 'login')
{
echo json_encode('{"error": 2000, "msg": "You must be logged in to do that."}') ;
return false ;
}
这对于Ajax来说很好,但是如果输入了url就不起作用了。$components[0]!='“访问”etc只是在用户处于登录屏幕时停止执行此条件
我如何做到这一点而不影响Ajax调用,也不只是在用户访问被禁止的url时回显错误消息
$UserName = "username";
$PassWord = "password";
if ($_SERVER['PHP_AUTH_USER'] != $UserName || $_SERVER['PHP_AUTH_PW'] != $PassWord) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.1 401 Unauthorized');
die('Your username and password is incorrect');
// or you can redirect user if username or password is incorrect
header("Location:"your redirecting url);
}
请使用此代码,它可能会对您有所帮助
要了解有关php身份验证的更多信息,请参阅以下链接:
我如何做到这一点而不影响Ajax调用,也不只是在用户访问被禁止的url时回显错误消息
$UserName = "username";
$PassWord = "password";
if ($_SERVER['PHP_AUTH_USER'] != $UserName || $_SERVER['PHP_AUTH_PW'] != $PassWord) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.1 401 Unauthorized');
die('Your username and password is incorrect');
// or you can redirect user if username or password is incorrect
header("Location:"your redirecting url);
}
实现这一点有多种方法,让我们在这里讨论两种方法:
检查推荐人
首先,您可以检查HTTP referer,浏览器将链接到当前页面的页面的URL作为HTTP头发送
请看一下这个(缩短的)HTTP请求http://foo.invalid/blah/?action=newfolder.php
,当用户单击表单/链接时
要求
标题
如果用户直接打开http://foo.invalid/blah/?action=newfolder.php
,将不存在referer字段
来源
现在,请求将包含自定义的X-Requested-With
标题,如果缺少标题,您可以假设页面是通过输入URL打开的
<?php
if (empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
// Redirect to login (X-Requested-With empty)
} else {
// Show JSON warning (X-Requested-With not empty)
}
?>
我喜欢自定义标题的想法,明天我会尝试一下,让您知道它的进展情况!
<?php
if (empty($_SERVER['HTTP_REFERER'])) {
// Redirect to login (Referer empty)
} else {
// Show JSON warning (Referer not empty)
}
?>
var r = new XMLHttpRequest();
r.open('get', '/blah/?action=newfolder.php');
r.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
r.send(null);
<?php
if (empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
// Redirect to login (X-Requested-With empty)
} else {
// Show JSON warning (X-Requested-With not empty)
}
?>