我正在尝试创建一个登录门户,它会导致两个不同的页面,连接应该根据它登录的用户来进行,问题是无论输入什么用户名,只要它在数据库中,它都会导致代码上写的最后一个位置,我不知道可能出了什么问题:
<?php
// connection to host and database
$host="localhost";
$username="dbusername";
$password="dbpass";
$db_name="dbname";
$tbl_name="members";
// connection
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//username and password sent from
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
//escape strings and stripslashes
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
//to count tables
$count=mysql_num_rows($result);
// **no matter the user it logs in, they will land in page2.php**
if($count==1){
($myusername == 'user1'){
header('location:page1.php');
}
elseif($myusername == 'user2'){
header('location:page2.php');
}
else {
echo "wrong username or password";
}
另一件事是,我无法通过session_start();
安全连接到page1.php或page2.php,因为它不需要登录即可进入页面,只需要知道链接,这是我在html启动前在page1.php的开头写的:
<?php
session_start();
if(!$myusername == 'user1'){
header("location:main_login.php");
}
?>
如有任何反馈,我们将不胜感激。谢谢
为什么我们鼓励良好的代码缩进:
if($count==1)
{
if ($myusername == 'user1') // you forgot an if here
{
header('location:page1.php');
}
else if ($myusername == 'user2')
{
header('location:page2.php');
}
else
{
echo "wrong username or password";
}
}//another closing bracket here
实际上不需要计算结果,因为无论如何都需要重定向脚本。因此,根据"用户名",重定向到特定页面或错误页面。
switch ($myusername) {
case 'user1':
$redirectPage = 'page1.php';
break;
case 'user2':
$redirectPage = 'page2.php';
break;
default:
$redirectPage = 'error.php';
}
header("Location: $redirectPage");
exit;
在page1.php中,如何初始化$myusername
变量?
您应该先尝试一些基本登录的示例。你似乎在关注这个,但我相信
a。这个例子很糟糕。
b。您编辑代码时没有理解其背后的逻辑。
请阅读w3school或php手册页上的会话示例。
登录页面
if (isset($_REQUEST["username"])) {
/*
usename & password verification here
you need to set $_SESSION["username"] in this code
*/
if ($_SESSION["username"] == "user1") {
header("Location: page1.php");
} else if $_SESSION["username"] == "user2") {
header("Location: page2.php");
}
} else {
/* login form here */
}
page1.php
if (!isset($_SESSION["username"])) {
header("Location: login.php");
} else {
/* content of page 1 here */
}
page2.php
if (!isset($_SESSION["username"])) {
header("Location: login.php");
} else {
/* content of page 2 here */
}