尝试通过一些数据库交互来学习 PHP,我正在尝试做一个“简单”(大多数事情都可以是相对的......)登录脚本,当我第一次尝试它时,我得到了一些关于 session_register 的错误,我现在明白这些错误已被弃用我试图将其更改为 $_SESSION['something'] = 'something';
我的数据库设置了一个用户,我可以很好地连接并选择正确的数据库,但是当我输入用户名和密码时,我会返回登录表单,当它失败时应该这样做。
当我使用已弃用的版本时,我确实有一些东西可以捕捉到错误的用户名或密码。我只有三个文件,main_login.php、checklogin.php 和 login_success.php,并将它们发布在下面。
main_login.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
<head>
<meta http-equiv='content-type' content='application/xhtml+xml; charset=UTF-8' />
<title>Login</title>
<!-- JAVASCRIPTS -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="script/jquery.js"></script>
<!-- CSS FILES -->
<link rel='stylesheet' type='text/css' href='css/default.css' />
</head>
<body>
<div id='wrapper'>
<div id='loginform'>
<form action="checklogin.php" method='post' id='login'>
Username: <br />
<input type='text' name='username' /><br />
Password: <br />
<input type='text' name='password' /><br />
<input type='submit' value='Login' />
</form>
</div>
</div>
</body>
检查登录.php
<?PHP
//Server/database settings
ob_start();
$host = "localhost";
$username = "root";
$password = "";
$db_name = "user";
$tbl_name = "userdata";
//Connect to the server and select the database
mysql_connect("$host", "$username", "$password") or die ("cannot connect");
mysql_select_db("$db_name") or die ("cannot select DB");
//Get the username and password from the login form
//Prevent SQL injections
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$username = stripslashes($username);
$password = stripslashes($password);
//$username = mysql_real_escape_string($username);
//$password = mysql_real_escape_string($password);
$sql = "SELECT * FROM $tbl_name WHERE username = '$username'
and password = '$password'";
$result = mysql_query($sql);
//Count the table row. 0 = No user exists
$count = mysql_num_rows($result);
//If $result is 1 the user exists
if($count == 1) {
$_SESSION['username'] = '$username';
$_SESSION['password'] = '$password';
header('location:login_success.php');
}
/* //If the result match the $username && $password, table row will be 1
if($count == 1) {
session_register('username');
session_register('password');
header('location:login_success.php');
}*/
//If it does not match, give a return message
else {
echo 'Wrong Username or Password';
}
ob_end_flush();
?>
和最后一个 login_success.php
<?PHP
session_start();
if (!isset($_SESSION['username'])) {
header('location:main_login.php');
}
?>
<html>
<body>
Login Successful
</body>
</html>
这只是让我回到登录页面:/
此外,如果有人注意到任何可能容易受到 SQL 注入攻击的代码,请随时指出并建议我应该做什么。