我将如何去,使它,当我登录上的index.html页面,它通过sql数据库,就像它在其他脚本


How would i go about, making it so that when i log in on the index.html page it goes through to the sql database like it does in the other scripts

我才刚刚开始学习如何编程,大多数代码不是原创的,它们来自教程和东西。我正在用它来学习它是如何结合在一起的。

我一直有麻烦实现php和mysql脚本到主HTML页面。

**我一直在使用WAMP

这是index.html


     <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
        <title>Bootstrap 101 Template</title>
        <!-- Bootstrap -->
        <link href="css/bootstrap.min.css" rel="stylesheet">
        <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and 
media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
          <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->
    <style type="text/css">
      .box{
        background-color: #d3d3d3;
        border: 1px solid grey;
      }
    </style>
      </head>
      <body>
        <div class="navbar navbar-inverse">
          <div class="container">
            <div class="navbar-header">
              <a href="" class="navbar-brand">Insanity and Calamity</a>
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                  <span class="sr-only">Toggle navigation</span>
                  <span class="icon-bar"></span> 
                  <span class="icon-bar"></span>
                  <span class="icon-bar"></span>
              </button>
            </div>
            <div class="collapse navbar-collapse">
              <ul class="nav navbar-nav">
                <li class="active"><a href="">Andrew</a></li>
                <li><a href="">Tommy</a></li>
                <li><a href="">Jayme</a></li>
              </ul>
               <ul class="nav pull-right">
              <li><a href="register.php">Sign Up</a></li>
              <li class="divider-vertical"></li>
              <li class="dropdown">
                <a class="dropdown-toggle" href="#" data-toggle="dropdown">Sign In <strong class="caret"></strong></a>
                <div class="dropdown-menu" style="padding: 15px; padding-bottom: 0px;">
            <form action="login.php" method="post" accept-charset="UTF-8">
                <input id="user_username" style="margin-bottom: 15px;" type="text" name="user[username]" size="30" />
                <input id="user_password" style="margin-bottom: 15px;" type="password" name="user[password]" size="30" />
                 <input id="user_remember_me" style="float: left; margin-right: 10px;" type="checkbox" name="user[remember_me]" value="1" />
                 <label class="string optional" for="user_remember_me"> Remember me</label>
                <input class="btn btn-primary" style="clear: left; width: 100%; height: 32px; font-size: 13px;" type="submit" name="commit" value="Sign In" />
            </form>
                </div>
              </li>
            </ul>
            </div>
          </div>
        </div>

       <h1>Hello, world!</h1>

        <div class="container">
          <div class="row">
            <div class="col-md-6 box">Holy cow</div>
            <div class="col-md-6 box">Holy cow</div>
          </div>
          <div class="row">
            <div class="col-md-4 box">Holy cow is super cool</div>
            <div class="col-md-4 box">Holy cow is super cool</div>
            <div class="col-md-4 box">Holy cow is super cool</div>
          </div>
        </div>
        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="jquery.min.js"></script>
        <!-- Include all compiled plugins (below), or include individual files as needed -->
        <script src="js/bootstrap.min.js"></script>
      </body>
    </html>

login。


<html>
<head>
    <title>User Login Form - PHP MySQL Ligin System | W3Epic.com</title>
</head>
<body>
<h1>User Login Form - PHP MySQL Ligin System | W3Epic.com</h1>
<?php
if (!isset($_POST['submit'])){
?>
<!-- The HTML login form -->
    <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
        Username: <input type="text" name="username" />
        Password: <input type="password" name="password" />
        <input type="submit" name="submit" value="Login" />
    </form>
<?php
} else {
    require_once("db_const.php");
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    # check connection
    if ($mysqli->connect_errno) {
        echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
        exit();
    }
    $username = $_POST['username'];
    $password = $_POST['password'];
    $sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
    $result = $mysqli->query($sql);
    if (!$result->num_rows == 1) {
        echo "<p>Invalid username/password combination</p>";
    } else {
        echo "<p>Logged in successfully</p>";
        // do stuffs
    }
}
?>      
</body>
</html>

Register.php


<html>
<head>
    <title>User registration form- PHP MySQL Ligin System | W3Epic.com</title>
</head>
<body>  
<h1>User registration form- PHP MySQL Ligin System | W3Epic.com</h1>
<?php
require_once("db_const.php");
if (!isset($_POST['submit'])) {
?>  <!-- The HTML registration form -->
    <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
        Username: <input type="text" name="username" /><br />
        Password: <input type="password" name="password" /><br />
        First name: <input type="text" name="first_name" /><br />
        Last name: <input type="text" name="last_name" /><br />
        Email: <input type="type" name="email" /><br />
        <input type="submit" name="submit" value="Register" />
    </form>
<?php
} else {
## connect mysql server
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    # check connection
    if ($mysqli->connect_errno) {
        echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
        exit();
    }
## query database
    #prepare data for insertion
    $username    = $_POST['username'];
    $password    = $_POST['password'];
    $first_name  = $_POST['first_name'];
    $last_name   = $_POST['last_name'];
    $email       = $_POST['email'];
    # check if username and email exist else insert
    $exists = 0;
    $result = $mysqli->query("SELECT username from users WHERE username = '{$username}' LIMIT 1");
    if ($result->num_rows == 1) {
        $exists = 1;
        $result = $mysqli->query("SELECT email from users WHERE email = '{$email}' LIMIT 1");
        if ($result->num_rows == 1) $exists = 2;    
    } else {
        $result = $mysqli->query("SELECT email from users WHERE email = '{$email}' LIMIT 1");
        if ($result->num_rows == 1) $exists = 3;
    }
    if ($exists == 1) echo "<p>Username already exists!</p>";
    else if ($exists == 2) echo "<p>Username and Email already exists!</p>";
    else if ($exists == 3) echo "<p>Email already exists!</p>";
    else {
        # insert data into mysql database
        $sql = "INSERT  INTO `users` (`id`, `username`, `password`, `first_name`, `last_name`, `email`) 
                VALUES (NULL, '{$username}', '{$password}', '{$first_name}', '{$last_name}', '{$email}')";
        if ($mysqli->query($sql)) {
            //echo "New Record has id ".$mysqli->insert_id;
            echo "<p>Registred successfully!</p>";
        } else {
            echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
            exit();
        }
    }
}
?>      
</body>
</html>

DB_const.php


<?php
# mysql db constants 
    const DB_HOST = 'localhost';
    const DB_USER = 'root';
    const DB_PASS = '';
    const DB_NAME = 'php_mysql_login_system';
?>

以您的代码为例,重点关注SESSION、散列密码、db。现在不需要几行使用参数获取mysqli绑定或css等,我留给您以下内容:

index . php

<?php
session_start();  // Start or resume the session
  if ($_POST['logout_yeehaw']) 
  { // form has been submitted to self from Logout button
    $_SESSION['proceed']=0; // bye bye, pseudo logout (true, you could kill all at once, please forgive)
    $_SESSION['userId']=-1;
    $_SESSION['fn']="";
  else 
  {
  } 
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Bootstrap 101 Template</title>
    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="js/jquery-2.1.4.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
<style type="text/css">
  .box{
    background-color: #d3d3d3;
    border: 1px solid grey;
  }
</style>
  </head>
  <body>
<?php 
include "showLoginStatus.php";
?>
    <div class="navbar navbar-inverse">
      <div class="container">
        <div class="navbar-header">
          <a href="" class="navbar-brand">Insanity and Calamity</a>
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span> 
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
          </button>
        </div>
        <div class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="">Andrew</a></li>
            <li><a href="">Tommy</a></li>
            <li><a href="">Jayme</a></li>
          </ul>
          <ul class="nav pull-right">
            <li><a href="register.php">Register</a></li>
            <li class="divider-vertical"></li>
            <li><a href="login.php">Login</a></li>
          </ul>
        </div>
      </div>
    </div>
   <h1>Hello, world!</h1>
    <div class="container">
      <div class="row">
        <div class="col-md-6 box">Holy cow cool</div>
        <div class="col-md-6 box">Holy cow cool</div>
      </div>
      <div class="row">
        <div class="col-md-4 box">Holy super cool</div>
        <div class="col-md-4 box">Holy super cool</div>
      </div>
    </div>
  </body>
</html>

login。

<?php
session_start();    // Start or resume the session
$bailOutGoHome = '<script type="text/javascript">';
$bailOutGoHome .= 'window.location = "'. "index.php".'"';
$bailOutGoHome .= '</script>';
$_SESSION['proceed']=0; // bye bye, pseudo logout (true, you could kill all at once, please forgive)
$_SESSION['userId']=-1;
$_SESSION['fn']="";
?>
<html>
<head>
    <title>User Login Form - PHP MySQL Login System | W3Epic.com</title>
</head>
<body>
<a href="index.php" >Home</a>
<h1>User Login Form - PHP MySQL Login System | W3Epic.com</h1>
<?php
if (!isset($_POST['submit'])){
?>
<!-- The HTML login form -->
<div style="background-color: #EDB495">You have just been logged out if you were logged in.</div>
    <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
        Username: <input type="text" name="username" />
        Password: <input type="password" name="password" />
        <input type="submit" name="submit" value="Login" />
    </form>
<?php
} else {
    require_once("db_const.php");
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    # check connection
    if ($mysqli->connect_errno) {
        echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
        exit();
    }
    $username = $_POST['username'];
    $password = $_POST['password'];
    // no way man, we don't LIKE the next line at all !
    //$sql = "SELECT userId,email from appusers WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
    $sql = "SELECT userId,email,password as dbhashxxx,first_name,last_name from appusers WHERE username ='{$username}' LIMIT 1";
    $result = $mysqli->query($sql);
    if ($result->num_rows == 1) {
        echo "1";
        $row = $result->fetch_array();
        $dbHash=$row['dbhashxxx'];
        if (password_verify($password, $dbHash)) {
            // password is valid, set some session stuff and leave to index.php
            $_SESSION['proceed']=1;
            $_SESSION['userId']=$row['userId'];
            $_SESSION['fn']=$row['first_name'] ." ". $row['last_name'];
            echo $bailOutGoHome;    // go home (index.php) avoids "headers already sent error"
        }       
    }
    // leave them stranded here, to slow down their robot
    echo "<p>Invalid username/password combination. You are evil, now go away.</p>";
}
?>
</body>
</html>

register.php

<html>
<head>
    <title>User registration form- PHP MySQL Login System | W3Epic.com</title>
</head>
<body> 
<a href="index.php" >Home</a> 
<h1>User registration form- PHP MySQL Login System | W3Epic.com</h1>
<?php
require_once("db_const.php");
if (!isset($_POST['submit'])) {
?>  <!-- The HTML registration form -->
    <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
        Username: <input type="text" name="username" /><br />
        Password: <input type="password" name="password" /><br />
        First name: <input type="text" name="first_name" /><br />
        Last name: <input type="text" name="last_name" /><br />
        Email: <input type="type" name="email" /><br />
        <input type="submit" name="submit" value="Register" />
    </form>
<?php
} else {
## connect mysql server
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    # check connection
    if ($mysqli->connect_errno) {
        echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
        exit();
    }
## query database
    #prepare data for insertion
    $username    = $_POST['username'];
    $password    = $_POST['password'];
    $first_name  = $_POST['first_name'];
    $last_name   = $_POST['last_name'];
    $email       = $_POST['email'];
    # check if username and email exist else insert
    $exists = 0;
    $result = $mysqli->query("SELECT username from appusers WHERE username = '{$username}' LIMIT 1");
    if ($result->num_rows == 1) {
        $exists = 1;
        $result = $mysqli->query("SELECT email from appusers WHERE email = '{$email}' LIMIT 1");
        if ($result->num_rows == 1) $exists = 2;    
    } else {
        $result = $mysqli->query("SELECT email from appusers WHERE email = '{$email}' LIMIT 1");
        if ($result->num_rows == 1) $exists = 3;
    }
    if ($exists == 1) echo "<p>Username already exists!</p>";
    else if ($exists == 2) echo "<p>Username and Email already exists!</p>";
    else if ($exists == 3) echo "<p>Email already exists!</p>";
    else {
        // see http://php.net/manual/en/function.password-hash.php
        $options = [
            'cost' => 12,   // let's splurge
        ];
        $hash = password_hash($password, PASSWORD_BCRYPT, $options);    // change to suit your concerns
        # insert data into mysql database
        # let the DB do the autoincrement of userId, don't pass NULL as 1st parameter
        $sql = "INSERT  INTO `appusers` (`username`, `password`, `first_name`, `last_name`, `email`) 
                VALUES ('{$username}', '{$hash}', '{$first_name}', '{$last_name}', '{$email}')";
        if ($mysqli->query($sql)) {
            //echo "New Record has id ".$mysqli->insert_id;
            echo "<p>Registered successfully!</p>";
        } else {
            echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
            exit();
        }
    }
}
?>      
</body>
</html>

showLoginStatus.php

<?php 
if ($_SESSION['proceed']==1) {
  echo "<div style='"background-color: #A2ED95'">";
  echo "You are logged in. Welcome ".$_SESSION['fn'].", userId=".$_SESSION['userId'];
  echo "<form method=post action='"". $_SERVER['PHP_SELF'] ."'">";  
  echo "<input type=hidden name=logout_yeehaw value=1>";
  echo "<input type='submit' name='logout' value='Logout' />";
  echo "</form></div>"; 
}
else
  echo "<div style='"background-color: #EDB495'">You are not logged in.</div>";

db_const.php

<?php
# mysql db constants 
    const DB_HOST = 'localhost';
    const DB_USER = 'dbuser1';
    const DB_PASS = 'newpassword';
    const DB_NAME = 'login_system';
?>

create database login_system;
use login_system;
-- drop table appusers;
create table appusers
(   -- does not care about saving user SALT
    -- remember that the cleartext password, the cost, and SALT are ALL baked into hash
    -- so as far as I am concerned, the SALT is a throw-away, after user one-time gen of it
    userId int auto_increment primary key,
    username varchar(20) not null,
    password varchar(255) not null, -- the hash, maybe blowfish, maybe not, look at code
    first_name varchar(50) not null,
    last_name varchar(50) not null,
    email varchar(100) not null
);
-- truncate table appusers;
-- note : despite the below, cleartext passwords will not be used
insert appusers(username,password,first_name,last_name,email) values ('andrew','cleartext','andrew','smith','andrew@gmail.com');
select * from appusers;
+--------+----------+--------------------------------------------------------------+------------+------------+-----------------+
| userId | username | password                                                     | first_name | last_name  | email           |
+--------+----------+--------------------------------------------------------------+------------+------------+-----------------+
|      1 | user1    | $2y$11$mp34MpHbhAcbN5YVlUBh4eTv0HMxuJJbvWhFKdtfkMDyhJpwnBCpG | Fred       | Gibbons    | f@g.com         |
|      2 | user2    | $2y$11$8dkjzLghFqU4nXSPPFdsa.nLvlw.EvdgxvYe5FbGsB7mx4BBRAqwy | Kelly      | Hartshorne | kelly@gmail.com |
|      3 | user3    | $2y$12$rk66cxOSRLUjIDKVU2EFq.Zz8T06qdEuzC4i3lKAi84IpGSKcGV8. | joe        | schmoe     | j               |
+--------+----------+--------------------------------------------------------------+------------+------------+-----------------+   
create user 'dbuser1'@'localhost' identified by 'newpassword';
select user,host,password from mysql.user where user='dbuser1';
+---------+-----------+-------------------------------------------+
| user    | host      | password                                  |
+---------+-----------+-------------------------------------------+
| dbuser1 | localhost | *Fxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx |
+---------+-----------+-------------------------------------------+
grant all on login_system.* to 'dbuser1'@'localhost';