I have a login page that when you login in successfully you will be redirected to a page called gallery.html
. However, when you type in the url with /gallery.html it will take you to the page that im trying to secure with logging in. What's the best way to use a conditional statement to prevent the page from being opened by typing in the exact URL? like a check before the page starts to load,
8 回答
很简单,session
在登录时使用变量,gallery.html
如果设置了会话 ID,则将用户重定向到,否则重定向到登录页面,类似这样
if($_SESSION['userid']){
header( 'Location: gallery.html' ) ;
exit();
}elseif($_SESSION['userid'] == ''){
header( 'Location: login.html' ) ;
exit();
}
我喜欢创建一个函数来处理这种事情:
function loggedin() {
if ( isset($_SESSION['user_id']) ) {
return true;
} else {
return false;
}
}
或者使用三元运算符更短的东西:
function loggedin() {
return (isset($_SESSION['user_id'])) ? true : false;
}
现在进行检查,只需在 if 语句中调用该函数:
if ( loggedin() ) {
// only logged in users can see this
}
或者
if ( !logged_in() ) {
// only users who aren't looged in can see this
}
比if (!isset($_SESSION['user_id'])) {
每次都输入类似的东西要容易得多!
如果您不想向匿名用户显示gallery.html,请在页面顶部使用此代码
if(!isset($_SESSION['your_user_login_id']))
{
//redirect to home page
}
此代码将阻止匿名用户查看此页面。
Use $_SESSION variable in gallery.php to check if the $_SESSION is set.
Although, I believe you will have to change the file name from gallery.html to gallery.php
<?php
if (!isset($_SESSION['secret_variable'])
{
echo "<br/>Error Message<br/>";
return;
}
?>
Continue with the rest of the code. If the user access the gallery.php by specifying the URL, he/she will end up with Error Message
.
The $_SESSION['secret_variable']
should be set after you figure out that the user has a valid username and password to ensure a valid login.
Thanks.. :)
您需要在会话中设置您的登录状态,并在您的待保护页面中检查会话。
<?php
session_start();
if (!isset($_SESSION['login_status'])) {
// Add permission denied message or redirect back to the login page
}
?>
但是,这可以在 PHP 页面中完成,而不是在具有 .html 扩展名的页面中完成(除非您使用“AddType x-httpd-php .html”指令明确指定了 Web 服务器配置。)
最简单的方法是使用 php。将您的gallery.html 保存为gallery.php 或在所有编码之前在gallery.html 页面顶部输入以下代码。然后使用 SESSION 变量(此处为 $_SESSION['userID'])来存储当前登录详细信息。
<?php
if(! isset($_SESSION['userID'])){ //userID or something to identify the user
header('Location:login.php'); //redirects to the login page
}else{
header('Location:gallery.php'); //redirect to the gallery.php for valid login
}
?>
There is no way of preventing someone from typing in the URL and requesting the page. THe only thing you'll be able to do is check if they are logged in on the page itself.
用户登录后,您必须设置 cookie 或会话。因此,您将为用户设置会话或 cookie。每次输入该特定 url 时,您必须检查会话以显示该页面或重定向到登录页面