我正在使用PHP 7和HTML 5创建一个电子商务站点。输入登录详细信息时,admin.php只会刷新,并且不会重定向到index.php。
我已经尝试使用实际的cookie,尽管出于安全原因,我宁愿只使用会话cookie。
ADMIN LOGIN.php CODE
<?php
session_start();
if(isset($_SESSION["manager"])){
header("location: index.php");
exit();
}
?>
<?php
if (isset($_POST["username"])&&isset($_POST["password"])){
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]);
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]);
include "../storescripts/connect_to_mysql.php";
//$sqlquery =
$sql = mysqli_query($con, "SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1");
$existCount=mysqli_num_rows($sql);
if($existCount == 1){
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: index.php");
exit();
} else {
// code...
echo 'Invalid Log In Credentials<br><br>';
echo'<a href="index.php">Click Here To Re-Enter Credentials</a>';
exit();
}
}
?>
INDEX.php CODE
<?php
session_start();
if (!isset($_SESSION["manager"])){
header("location: admin_login.php");
exit();
}
$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]);
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]);
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]);
include "../storescripts/connect_to_mysql.php";
$sql = mysqli_query($con, "SELECT * FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password' LIMIT 1");
$existCount = mysqli_num_rows($sql);
if ($existCount == 0){
header("location: ../index.php");
exit();
}
?>
我希望一旦设置了会话cookie,页面就会重定向到index.php,但是它不会这样做。
答案 0 :(得分:0)
您必须更改您的重定向呼叫。我建议您将该逻辑封装在一个函数中。
function redirectTo($uri)
{
header('Location: '.$uri); // Where to redirect.
http_response_code(301); // The response code to redirection.
exit(); // End of script
}
然后在您的客户端代码中,重定向到index.php
redirectTo('/index.php'); // Note the removal of the dots. Your file must be relative to your document_root, not your filesystem.
完成。
PS:作为旁注,请勿将其视为人身攻击;这不是用PHP编码的正确方法。请查看:https://phptherightway.com/。现在,您必须使用正确的HTTP抽象。检查Zend Diactoros。 :)