我无法让登录表单连接到mySQL数据库 [英] I cannot get my login form to connect interact properly with mySQL database

查看:142
本文介绍了我无法让登录表单连接到mySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要发生的事情是用户使用用户名和密码登录,并且该数据是否与数据库中的数据匹配。当我尝试我没有得到任何错误,但它不起作用。我在Dreamweaver中使用html和php,以及使用phpMyAdmin的WAM。我将包含表单文档和随附的php文档:

loginpage.php

 <?php 
include('login.php'); //包括登录脚本

if(isset($ _ SESSION ['login_user'])){
header(location:index.php);
}
?>

< table width =15pxborder =0>
< form form action ='login.php'method ='POST'>
< tr>
< td>使用者名称< / td>
< td>< input type =textname =username/>< / td>
< / tr>
< tr>
< td>密码< / td>
< td>< input type =passwordname =password/>< / td>
< / tr>
< tr>
< td>< input type =submitname =submitvalue =submit/>< / td>
< / tr>
< / form>






登录。 php

 < html> 
< head>
< title>登入< / title>
< / head>
< body>
<?php
session_start(); //开始会话
$ error =''; ($ _ POST ['submit'])){
if(empty($ _ POST ['username'])|| empty($ _ POST ['password '])){
$ error =用户名或密码无效;
}
else
{
//定义$ username和$ password
$ username = $ _ POST ['username'];
$ password = $ _ POST ['password'];
//通过传递server_name,user_id和password作为参数来建立与服务器的连接
$ hostname =localhost;
$ database =boost;
$ username =root;
$ password =;
$ localhost = mysqli_connect($ hostname,$ username,$ password,$ database);
if(mysqli_connect_errno())
{
die(Connection Failed.mysqli_error());
}
// SQL查询获取注册用户的信息并查找用户匹配。
$ sql =SELECT * FROM`users`;
$ query = mysqli_query($ localhost,$ sql);
if(!$ query)
{
die(Query Failed.mysqli_error($ localhost));
}
$ rows = mysqli_num_rows($ query);
if($ rows == 1){
$ _SESSION ['login_user'] = $ username; //初始化会话
echo你现在已经登录了!;
} else {
$ error =用户名或密码无效;
}
mysqli_close($ localhost); //关闭连接
}
}
?>
< / body>
< / html>


解决方案

这个答案适用于哈希, password_hash() password_verify()。对于mysqli和pdo。在底部的链接有进一步的链接和关于盐等的一些语言。

直接使用用户提供的数据选择和插入是至关重要的。相反,绑定参数并调用准备好的语句来避免sql注入攻击。永远不要将密码保存在数据库中的明文(明文)中。相反,它们应该通过单向散列发送。



另请注意。这显示注册哈希和登录验证。它是没有完整的功能功能我试图在Codecanyon上花费十块钱...这样它显示一个电子邮件地址(登录)的重新注册已经存在,是否更新,请关注你。在这种情况下,由于在db中设置了唯一键,插入操作只会失败。我把这些留给你,读者,做查找,并说'电子邮件已经注册'。



架构



  CREATE TABLE`user_accounts2`(
`id` int(11)NOT NULL AUTO_INCREMENT,
`email` varchar(100)NOT NULL,
`password` varchar(255)NOT NULL,
PRIMARY KEY(`id`),
唯一键(email) - 最好是这种情况
)ENGINE = InnoDB;

运行register.php并保存用户之后,数据可能如下所示:

  select * from user_accounts2; 
+ ---- + ----------- + ---------------------------- ---------------------------------- +
| id |电子邮件|密码|
+ ---- + ----------- + ---------------------------- ---------------------------------- +
| 1 | d@d.com | $ 2y $ 10 $ U6.WR.tiOIYNGDWddfT7kevJU8uiz8KAkdxXpda9e1xuplhC / eTJS |
+ ---- + ----------- + ---------------------------- ---------------------------------- +

lockquote



register.php



 <?php 
mysqli_report(MYSQLI_REPORT_ALL);
error_reporting(E_ALL); //报告所有PHP错误
ini_set(display_errors,1); //显示它们
session_start();

if(isset($ _ SESSION ['userid'])!=){
//您已经登录,因为会话已设置
header(Location :safe.php); //注意,这个重定向会在该页面的顶部
// ...并在那里验证会话状态,因此不会执行任何技巧
//无技巧和噱头$ b $如果(isset($ _ POST ['register'])){
$ email = $ _POST ['email']; b}


$ ctPassword = $ _POST ['password']; //用户
$ hp = password_hash($ ctPassword,PASSWORD_DEFAULT)的明文密码; //使用明文字母1对密码进行散列

//假装以下内容被锁定在文件库中并加载但是硬编码在这里
$ host =yourhostname;
$ dbname =dbname;
$ user =dbuser;
$ pwd =密码;
$ port = 3306; //随之而来,所以我不需要查看
下面的param命令// end end

try {
$ mysqli = new mysqli($ host, $ user,$ pwd,$ dbname,$ port);
if($ mysqli-> connect_error){
die('Connect Error('。$ mysqli-> connect_errno。')'。$ mysqli-> connect_error);
}
// echo我已连线并感到高兴。< br />;
$ query =INSERT INTO user_accounts2(email,password)VALUES(?,?);
$ stmt = $ mysqli-> prepare($ query);

//注意下面的2 s,s是字符串
$ stmt-> bind_param(ss,$ email,$ hp); //永远不要使用未经过消毒的用户提供的数据。绑定
$ stmt-> execute();
//密码保存为哈希值,将通过password_verify()在登录页面进行验证
$ iLastInsertId = $ mysqli-> insert_id; //做一些特殊的事情(或不)
//重定向到某个登录页面(现在你只是坐在这里)
$ stmt-> close();
$ mysqli-> close();
} catch(mysqli_sql_exception $ e){
throw $ e;
}
}
?>
< html>
< head>
< title>注册新用户< / title>
< / head>
< body>
< div id =reg-form>
< form method =post>
< table>
< tr>
< td>< input type =emailname =emailplaceholder =Emailrequired />< / td>
< / tr>
< tr>
< td>< input type =passwordname =passwordplaceholder =Passwordrequired />< / td>
< / tr>
< tr>
< td><按钮类型=提交名称=注册>注册< /按钮>< / td>
< / tr>
< tr>
< td>< a href =index.php>正常登入此处< / a>< / td>
< / tr>
< / table>
< / form>
< / div>
< / body>
< / html>



login.php



 <?php 
mysqli_report(MYSQLI_REPORT_ALL);
error_reporting(E_ALL); //报告所有PHP错误
ini_set(display_errors,1); //显示它们
session_start();

if(isset($ _ SESSION ['userid'])!=){
//您已经设置会话已经登录
header(Location :safe.php); //注意,这个重定向会在该页面的顶部
// ...并在那里验证会话状态,因此不会执行任何技巧
//无技巧和噱头$ b $如果(isset($ _ POST ['login'])){
$ email = $ _POST ['email']; b}


$ ctPassword = $ _POST ['password']; // cleartext来自用户

的密码//假装以下内容已被锁定在Vault中并且已加载但硬编码
$ host =yourhostname;
$ dbname =dbname;
$ user =dbuser;
$ pwd =密码;
$ port = 3306; //随之而来,所以我不需要查看
下面的param命令// end end

try {
$ mysqli = new mysqli($ host, $ user,$ pwd,$ dbname,$ port);
if($ mysqli-> connect_error){
die('Connect Error('。$ mysqli-> connect_errno。')'。$ mysqli-> connect_error);
}
// echo我已连线并感到高兴。< br />;
$ query =选择ID,电子邮件,密码from user_accounts2 where email =?;
$ stmt = $ mysqli-> prepare($ query);

//注意下面的s,s代表字符串
$ stmt-> bind_param(s,$ email); //永远不要使用未经过消毒的用户提供的数据。绑定
$ stmt-> execute();
$ result = $ stmt-> get_result();
if($ row = $ result-> fetch_array(MYSQLI_ASSOC)){
$ dbHashedPassword = $ row ['password'];
if(password_verify($ ctPassword,$ dbHashedPassword)){
echoright,userid =;
$ _SESSION ['userid'] = $ row ['id'];
echo $ _SESSION ['userid'];
//重定向到safe.php(注意在这个文件的顶部关于它的保护措辞)
}
else {
echowrong;
//可能会过度杀伤这里,但在logout.php
//清除$ _SESSION ['userid']
}
}
else {
回声'没有这样的记录';
}
//记住,没有遍历行,因为有1或0(电子邮件具有唯一键)
//也是,散列是db中的单向函数。一旦你散列和做插入
//几乎没有回来从数据库明文与它。你只需验证它

$ stmt-> close();
$ mysqli-> close();
} catch(mysqli_sql_exception $ e){
throw $ e;
}
}
?>
< html>
< head>
< title>登入< / title>
< / head>
< body>
< div id =reg-form>
< form method =post>
< table>
< tr>
< td>< input type =emailname =emailplaceholder =Emailrequired />< / td>
< / tr>
< tr>
< td>< input type =passwordname =passwordplaceholder =Passwordrequired />< / td>
< / tr>
< tr>
< td><按钮类型=提交名称=登录>登录< /按钮>< / td>
< / tr>
< / table>
< / form>
< / div>
< / body>
< / html>




pdo section below




当我有时间时,可能明天,但现在我指向你这个我的回答


What I would like to happen is for a user to log in with a username and password, and if that data matches up with the one in the databse. When I try I don't get any errors, but it does not work. I am using html and php in dreamweaver, and WAM with phpMyAdmin. I will include both the form document and the php document that goes with it:

loginpage.php

 <?php
include('login.php'); // Includes Login Script

if(isset($_SESSION['login_user'])){
header("location: index.php");
}
?>

<table width="15px" border="0">
<form form action='login.php' method='POST'>
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
  <td><input type="submit" name="submit" value="submit"/></td>
</tr>
</form>

login.php

  <html>
   <head>
    <title>Login</title>
  </head>
  <body>
  <?php 
    session_start(); // Starting Session
    $error=''; // Variable To Store Error Message
    if (isset($_POST['submit'])) {
    if (empty($_POST['username']) || empty($_POST['password'])) {
    $error = "Username or Password is invalid";
    }
    else
    {
    // Define $username and $password
    $username=$_POST['username'];
    $password=$_POST['password'];
    // Establishing Connection with Server by passing server_name, user_id   and password as a parameter
    $hostname= "localhost";
    $database = "boost";
    $username = "root";
    $password = "";
    $localhost = mysqli_connect($hostname, $username, $password, $database);
    if(mysqli_connect_errno())
    {
        die("Connection Failed".mysqli_error());
    }
    // SQL query to fetch information of registerd users and finds user match.
    $sql = "SELECT * FROM `users`";
    $query = mysqli_query($localhost,$sql);
    if(!$query)
    {
        die("Query Failed".mysqli_error($localhost));
    }
    $rows = mysqli_num_rows($query);
    if ($rows == 1) {
    $_SESSION['login_user']=$username; // Initializing Session
    echo "You are now logged on!";
    } else {
    $error = "Username or Password is invalid";
    }
    mysqli_close($localhost); // Closing Connection
    }
    }
  ?>
 </body>
 </html>

解决方案

This answer is for hashing, password_hash(), and password_verify(). For both mysqli and pdo. The link at the bottom has further links and some language about salts and the like.

It is crucial to not use user-supplied data directly with selects and inserts. Rather, bind parameters and call prepared statements to Avoid sql injection attacks. Passwords should never be saved in the clear (cleartext) in databases. Rather, they should be sent through one-way hashes.

Also note. This is showing registration hashing and login verify. It is not full blown functionality I am trying to hock on codecanyon for ten bucks ... such that it shows a re-registration of an email address (the login) already exists, does updates, mind you. In that case the insert will simply fail due to the unique key set in place in the db. I leave that to you, the reader, to do the lookup, and say 'email already registered.'

Schema

CREATE TABLE `user_accounts2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(100) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  unique key(email) -- that better be the case
) ENGINE=InnoDB;

After running through register.php and saving a user, the data might look like this:

select * from user_accounts2;
+----+-----------+--------------------------------------------------------------+
| id | email     | password                                                     |
+----+-----------+--------------------------------------------------------------+
|  1 | d@d.com   | $2y$10$U6.WR.tiOIYNGDWddfT7kevJU8uiz8KAkdxXpda9e1xuplhC/eTJS |
+----+-----------+--------------------------------------------------------------+

mysqli section first

register.php

<?php
    mysqli_report(MYSQLI_REPORT_ALL);
    error_reporting(E_ALL); // report all PHP errors
    ini_set("display_errors", 1); // display them
    session_start();

    if(isset($_SESSION['userid'])!="") {
        // you are already logged in as session has been set
        header("Location: safe.php");   // note that this re-direct will at the top of that page
        // ... and there to verify the session state so no tricks can be performed
        // no tricks and gimmicks
    }

    if(isset($_POST['register'])) {
        $email = $_POST['email'];
        $ctPassword = $_POST['password'];   // cleartext password from user
        $hp=password_hash($ctPassword,PASSWORD_DEFAULT); // hashed password using cleartext one

        // pretend the following is locked in a vault and loaded but hard coded here
        $host="yourhostname";
        $dbname="dbname";
        $user="dbuser";
        $pwd="password";
        $port=3306; // comes along for the ride so I don't need to look up param order below
        // end pretend

        try {
            $mysqli= new mysqli($host, $user, $pwd, $dbname,$port);
            if ($mysqli->connect_error) {
                die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
            }
            //echo "I am connected and feel happy.<br/>";
            $query = "INSERT INTO user_accounts2(email,password) VALUES (?,?)";
            $stmt = $mysqli->prepare($query);

            // note the 2 s's below, s is for string
            $stmt->bind_param("ss", $email,$hp);    // never ever use non-sanitized user supplied data. Bind it
            $stmt->execute();
            // password is saved as hashed, will be verified on login page with password_verify()
            $iLastInsertId=$mysqli->insert_id;  // do something special with this (or not)
            // redirect to some login page (for now you just sit here)
            $stmt->close(); 
            $mysqli->close();
        } catch (mysqli_sql_exception $e) { 
            throw $e; 
        } 
    }
?>
<html>
<head>
<title>Register new user</title>
</head>
<body>
<div id="reg-form">
<form method="post">
    <table>
        <tr>
        <td><input type="email" name="email" placeholder="Email" required /></td>
        </tr>
        <tr>
        <td><input type="password" name="password" placeholder="Password" required /></td>
        </tr>
        <tr>
        <td><button type="submit" name="register">Register</button></td>
        </tr>
        <tr>
        <td><a href="index.php">Normal Login In Here</a></td>
        </tr>
    </table>
</form>
</div>
</body>
</html>

login.php

<?php
    mysqli_report(MYSQLI_REPORT_ALL);
    error_reporting(E_ALL); // report all PHP errors
    ini_set("display_errors", 1); // display them
    session_start();

    if(isset($_SESSION['userid'])!="") {
        // you are already logged in as session has been set
        header("Location: safe.php");   // note that this re-direct will at the top of that page
        // ... and there to verify the session state so no tricks can be performed
        // no tricks and gimmicks
    }

    if(isset($_POST['login'])) {
        $email = $_POST['email'];
        $ctPassword = $_POST['password'];   // cleartext password from user

        // pretend the following is locked in a vault and loaded but hard coded here
        $host="yourhostname";
        $dbname="dbname";
        $user="dbuser";
        $pwd="password";
        $port=3306; // comes along for the ride so I don't need to look up param order below
        // end pretend

        try {
            $mysqli= new mysqli($host, $user, $pwd, $dbname,$port);
            if ($mysqli->connect_error) {
                die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
            }
            //echo "I am connected and feel happy.<br/>";
            $query = "select id,email,password from user_accounts2 where email=?";
            $stmt = $mysqli->prepare($query);

            // note the "s" below, s is for string
            $stmt->bind_param("s", $email); // never ever use non-sanitized user supplied data. Bind it
            $stmt->execute();
            $result = $stmt->get_result();
            if ($row = $result->fetch_array(MYSQLI_ASSOC)) {
                $dbHashedPassword=$row['password'];
                if (password_verify($ctPassword,$dbHashedPassword)) {
                    echo "right, userid=";
                    $_SESSION['userid']=$row['id'];
                    echo $_SESSION['userid'];
                    // redirect to safe.php (note safeguards verbiage at top of this file about it)
                }
                else {
                    echo "wrong";
                    // could be overkill here, but in logout.php
                    // clear the $_SESSION['userid']
                }
            }
            else {
                echo 'no such record';
            }
            // remember, there is no iterating through rows, since there is 1 or 0 (email has a unique key)
            // also, hashes are one-way functions in the db. Once you hash and do the insert
            // there is pretty much no coming back to cleartext from the db with it. you just VERIFY it

            $stmt->close(); 
            $mysqli->close();
        } catch (mysqli_sql_exception $e) { 
            throw $e; 
        } 
    }
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<div id="reg-form">
<form method="post">
    <table>
        <tr>
        <td><input type="email" name="email" placeholder="Email" required /></td>
        </tr>
        <tr>
        <td><input type="password" name="password" placeholder="Password" required /></td>
        </tr>
        <tr>
        <td><button type="submit" name="login">Login</button></td>
        </tr>
    </table>
</form>
</div>
</body>
</html>

pdo section below

When I have time, probably tomorrow, but for now I point you to this Answer of mine.

这篇关于我无法让登录表单连接到mySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆