PHP MySQL 登录
这个教程演示了如何用 MySQL 数据库创建一个登录页面。在进入代码部分之前,您需要特殊权限来创建或删除一个 MySQL 数据库。所以假设您有根用户访问权限,您可以使用 mysql mysqladmin 二进制文件创建任何数据库。
Config.php
Config.php 文件包含有关 MySQL 数据库配置的信息。
<?php
define('DB_SERVER', 'localhost:3036');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'rootpassword');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
login.php
登录PHP中包含关于PHP脚本和HTML脚本的信息,用于执行登录操作。
<?php
include("config.php");
session_start();
if(_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from formmyusername = mysqli_real_escape_string(db,_POST['username']);
mypassword = mysqli_real_escape_string(db,_POST['password']);sql = "SELECT id FROM admin WHERE username = 'myusername' and passcode = 'mypassword'";
result = mysqli_query(db,sql);row = mysqli_fetch_array(result,MYSQLI_ASSOC);active = row['active'];count = mysqli_num_rows(result);
// If result matchedmyusername and mypassword, table row must be 1 row
if(count == 1) {
session_register("myusername");
_SESSION['login_user'] =myusername;
header("location: welcome.php");
}else {
error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login Page</title>
<style type = "text/css">
body {
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
}
label {
font-weight:bold;
width:100px;
font-size:14px;
}
.box {
border:#666666 solid 1px;
}
</style>
</head>
<body bgcolor = "#FFFFFF">
<div align = "center">
<div style = "width:300px; border: solid 1px #333333; " align = "left">
<div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>Login</b></div>
<div style = "margin:30px">
<form action = "" method = "post">
<label>UserName :</label><input type = "text" name = "username" class = "box"/><br /><br />
<label>Password :</label><input type = "password" name = "password" class = "box" /><br/><br />
<input type = "submit" value = " Submit "/><br />
</form>
<div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php echoerror; ?></div>
</div>
</div>
</div>
</body>
</html>
welcome.php
成功登录后,将显示欢迎页面。
<?php
include('session.php');
?>
<html">
<head>
<title>Welcome </title>
</head>
<body>
<h1>Welcome <?php echo $login_session; ?></h1>
<h2><a href = "logout.php">Sign Out</a></h2>
</body>
</html>
Logout.php
退出页面提供了关于如何从登录会话中退出的信息。
<?php
session_start();
if(session_destroy()) {
header("Location: login.php");
}
?>
session.php
Session.php会验证会话,如果没有会话,它将重定向到登录页面。
<?php
include('config.php');
session_start();
user_check =_SESSION['login_user'];
ses_sql = mysqli_query(db,"select username from admin where username = 'user_check' ");row = mysqli_fetch_array(ses_sql,MYSQLI_ASSOC);login_session = row['username'];
if(!isset(_SESSION['login_user'])){
header("location:login.php");
die();
}
?>
极客教程