main_login.php如何创建一个具有HTML,PHP和MySQL数据库的登录表单我已创建如下所示。
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="password" id="mypassword"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
checklogin.php
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="database"; // Database name
$tbl_name="login"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$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);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// 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:login_success.php");
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
?>
login_success.php
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:login.php");
}
?>
<html>
<body>
Login Successful
</body>
</html>
它不工作。如果用户名和密码正确无误。我应该如何改正它?我真的不知道这段代码有什么问题,我非常感谢你的帮助!
您必须启动'session'在'checklogin.php'页面,因为你设置寄存器那里。 –
**警告**:如果您只是学习PHP,请不要学习过时的['mysql_query'](http://php.net/manual/en/function.mysql-query.php)界面。这很糟糕,并且已经在PHP 7中被删除了。像[PDO不是很难学的东西](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-php-pdo- for-database-access /)以及[PHP The Right Way](http://www.phptherightway.com/)等指南有助于解释最佳实践。确保**你的用户参数[妥善转义](http://bobby-tables.com/php),否则你将以严重的[SQL注入漏洞](http://bobby-tables.com/ )。 – tadman
**警告**:编写您自己的访问控制层并不容易,并且有很多机会使其严重错误。请不要在[Laravel](http://laravel.com/)等任何现代开发框架(http://codegeekz.com/best-php-frameworks-for-developers/)上编写自己的认证系统,内置了强大的[认证系统](https://laravel.com/docs/5.2/authentication)。绝对不要遵循[推荐的安全最佳实践](http://www.phptherightway.com/#security),也绝不要将密码存储为纯文本格式。 – tadman