我正在制作一个连接到数据库的网站和登录功能。我已经编写了脚本并且它登录和注销但它只是登录,即使表单字段为空,例如,如果我没有在用户名和密码字段中放置任何内容它仍然登录。我检查并测试了我的数据库是与服务器上的PHP文件连接。我在网上搜索后尝试了很多东西,但都浪费了我的时间,我仍然无法正常工作,
我的代码是:
<?php
if (isset($_POST['loginsubmit'])){
$query = "SELECT user_id, password FROM users WHERE username = '".$_POST['username']."'";
$result = mysql_query($query) or die (mysql_error());
$row = mysql_fetch_array($result);
if ($row['password'] == $_POST['pword']){
$_SESSION['id'] = $row['user_id'];
$_SESSION['loggedin'] = true;
}else{
$_SESSION['id'] = 0;
$_SESSION['loggedin'] = false;
}}
if (isset($_SESSION['loggedin'])==true){
echo "<p> Hello " . "$_POST[username]"." <a href='logout.php'>LogOut </a> </p>";
}else {
echo "<p>You are NOT logged in</p>\n";
}
我要做的是检查:
答案 0 :(得分:0)
查看“设置或不设置”方法是否适合您。除了不使用任何mysql_
函数之外,我还注意到了一些需要注意的事项:
<?php
// You probably have this, but make sure session_start() is on the top of page
session_start();
if (isset($_POST['loginsubmit'])){
// If you use PDO or mysqli_ with prepared statements,
// you don't need to escape the post, but in your case
// you do (sql injection hazard)
$query = "SELECT user_id, password FROM users WHERE username = '".mysql_real_escape_string($_POST['username'])."'";
$result = mysql_query($query) or die (mysql_error());
$row = mysql_fetch_array($result);
// You really need to insert encrypt/decrypt routine here for the password
// Storing plain-text passwords is bad news.
if (isset($row['password']) && ($row['password'] == $_POST['pword']))
$_SESSION['id'] = $row['user_id'];
// Don't even set a session attribute here.
// When you check stuff for logged in or logged out,
// you would just check if the $_SESSION['id'] is even set
// If it is, logged in, if not, then logged out
}
// The problem in your code is likely this line:
// if (isset($_SESSION['loggedin'])==true)
// Should be: if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true)
// That being said, I am not sure the point of setting session variables
// in the instance of not logged in.
// Check that it's set at all
if(isset($_SESSION['id']))
// You need to strip_tags or htmlspecialchars() this post
echo "<p> Hello " . htmlspecialchars($_POST['username'])." <a href='logout.php'>LogOut </a> </p>";
else
echo "<p>You are NOT logged in</p>\n";
?>