我正在学习PHP,我有问题得到以下代码正常工作。基本上登录页面显示正确,没有错误和变量似乎被正确分配,但在页面重新加载时,我只是得到相同的登录表单,似乎数据要么没有被传递,因此没有被采取行动。
我一遍又一遍地看代码,甚至尝试了不同的方法(产生了相同的结果!)所以如果有人能花点时间给我指出正确的方向,那就太好了。
有一件事可能是一个问题,我的服务器运行的是5.3.9,我正在使用的书是PHP5,所以也许我调用的一些函数已经被弃用了。这将是一个痛苦的…
<?php
include_once "common_db.inc";
$register_script = "register.php";
if (!isset ($userid)) {
login_form();
exit;
} else {
session_start();
session_register ("userid", "userpassword");
$username = auth_user ($_POST['userid'], $_POST['userpassword']);
if (!$username) {
$PHP_SELF = $_SERVER['PHP_SELF'];
session_unregister ("userid");
session_unregister ("userpassword");
echo "Failed to authorize. " .
"Enter a valid DX number and password." .
"Click the link below to try again.<br>'n";
echo "<a href='"$PHP_SELF'">login</a><br>";
echo "Click the following link to register<br>'n";
echo "<a href='"$register_script'">Register</a>";
exit;
} else {
echo "Welcome, $username!";
}
}
function login_form()
{
global $PHP_SELF;
?>
<form method="post" action="<?php echo "$PHP_SELF"; ?>">
<div align="center"><center>
<h3>Please login to use the page you requested</h3>
<table width="200" cellpadding="5">
<tr>
<th width="18%" align="right" nowrap>id</th>
<td width="82%" nowrap>
<input type="text" name="userid" />
</td>
</tr>
<tr>
<th width="18%" align="right" nowrap>password</th>
<td width="82%" nowrap>
<input type="password" name="userpassword" />
</td>
</tr>
<tr>
<td colspan="2" width="100%" nowrap>
<input type="submit" value="login" name="Submit" />
</td>
</tr>
</table>
</center>
</div>
</form>
<?php
}
function auth_user($userid, $userpassword)
{
global $dbname, $user_tablename;
$link_id = db_connect($dbname);
$query = "SELECT DXNumber FROM $user_tablename WHERE DXNumber = '$userid'
AND userpassword = password ('$userpassword')";
$result = mysql_query ($query);
if (!mysql_num_rows($result)){
return 0;
}else{
$query_data = mysql_fetch_row($results);
return $query_data[0];
}
}
?>
您没有定义$userid
或检查表单是否已提交。试一试:
if (!isset($_POST['userid'])) {
您在auth_user
函数中的查询需要看起来像这样:
$query = "SELECT DXNumber FROM $user_tablename WHERE DXNumber = '$userid' AND userpassword ='" . $userpassword."'";
同时,你对sql注入是开放的。你应该考虑使用PDO并防止它。
try
if (!isset $_POST['userid']) {
,看看是否有帮助。看起来$userid没有在分支之前设置。
(由于愚蠢的拼写检查而编辑)