我创建了下面的代码,让人们登录一个网站,但结果一直显示:
用户名或密码错误
我不知道怎么了。数据库中有一个名为"clients"的表,列名为"usernames"answers"password "。
<?php
$host = ""; // Host name
$username = ""; // Mysql username
$password = ""; // Mysql password
$db_name = ""; // Database name
$tbl_name = "clients"; // Table name
$con = mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$username = $_POST['myusername'];
$password = $_POST['mypassword'];
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql = "SELECT `username` FROM `clients` WHERE `username`='$myusername' and `password`='$mypassword'";
$result = mysql_query($sql) or die(mysql_error());
// Mysql_num_row is counting table row
if ($result) {
$count = mysql_num_rows($result);
}
else {
$count = 0;
}
// If result matched $myusername and $mypassword, table row must be 1 row
if ($count == 1) {
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:source/login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>
问题就在这里:
$username = $_POST['myusername'];
$password = $_POST['mypassword'];
$myusername = stripslashes($myusername); // Using uninitialized '$myusername'
$mypassword = stripslashes($mypassword); // Using uninitialized '$mypassword'
$myusername
和$mypassword
在传递给stripslashes()
时被初始化,因此结果总是空的。
要纠正这个问题,调整传递给stripslashes()
的变量名:
$myusername = stripslashes($username);
$mypassword = stripslashes($password);
修改如下:
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
:
$myusername = stripslashes($username);
$mypassword = stripslashes($password);
最好不要在会话中注册密码。更好的做法是使用用户的id来设置会话(比如在mysql表中,有:id、用户名、密码等)。这是一种更好、更安全的方法。然后,在需要登录的页面上,只需输入:
<?php
session_start();
if(!isset($_SESSION['id']) {
..... display error message and redirect user to login page....
}
?>
$ username = $ _POST['上的用户名都"dangillmor];
$password = $_POST['mypassword'];
试试这个
$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];