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