所以,我创建了一个网站及其登录系统。有一个登陆页面,一个“新帖子”页面和一个登录页面。如果没有登录[已解决],我不希望用户访问“新帖子”页面,但是,如果他将尝试在没有会话的情况下访问它,它会将他重定向到带有/ login /的登录页面?新的。 当他在地址栏中使用?new登录时,应将其重定向到“新帖子”页面,如果网址只是/ login /,则会将他带到登陆。 那是我试图做的代码:
if( $count == 1 && $row['userPass']==$password && isset($_POST["new"]) ) {
$_SESSION['user'] = $row['userId'];
header('Location:../new');
} else if ($count == 1 && $row['userPass']==$password) {
$_SESSION['user'] = $row['userId'];
header('Location:../');
}
else {
$errMSG = "Incorrect Credentials, Try again...";
}
这是完整的代码:
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($email)){
$error = true;
$emailError = "Please enter your email address.";
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
// if there's no error, continue to login
if (!$error) {
$password = hash('sha256', $pass); // password hashing using SHA256
$res=mysql_query("SELECT userId, userName, userPass FROM users WHERE userEmail='$email'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
if( $count == 1 && $row['userPass']==$password && isset($_POST["new"]) ) {
$_SESSION['user'] = $row['userId'];
header('Location:../new');
} else if ($count == 1 && $row['userPass']==$password) {
$_SESSION['user'] = $row['userId'];
header('Location:../');
}
else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
答案 0 :(得分:-1)
如果没有登录,我不希望用户访问“新帖子”页面[已解决]
我认为你已经通过做类似或类似的事情解决了这个问题。
if (!isset($_SESSION['user'])) {
header('Location:login.php');
}
我建议您将标题功能更改为此。让我们说新的帖子页面叫做new.php
header('Location:login.php?redirectto=new.php');
然后在您的登录页面代码中:
if( $count == 1 && $row['userPass']==$password && !empty($_GET["redirectto"]) ) {
$_SESSION['user'] = $row['userId'];
header('Location:'.$_GET["redirectto"]);
} else if ($count == 1 && $row['userPass']==$password) {
$_SESSION['user'] = $row['userId'];
header('Location:../');
}
else {
$errMSG = "Incorrect Credentials, Try again...";
}