By GokiSoft.com|
09:50 25/04/2022|
Học PHP
[Source Code] Bài tập - Tạo website bán hàng lư niệm - Login - Lập trình PHP/MySQL - C2108G3
Bài tập - Tạo website bán hàng lư niệm - Login - Lập trình PHP/MySQL
#readme.txt
Cấu trúc dự án:
- db
- config.php
- dbhelper.php
- utils
- utility.php
- init.php -> Khởi tạo CSDL + table trong database
- login.php
- register.php
- gift.php -> Hiển thị danh sách dữ liệu gift trong database
Kỹ thuật keep login:
login -> đăng nhập vào hệ thống
-> Login failed -> ...
-> Login thành công
- Sử dụng $_SESSION: keep login trong phiên làm việc
- generate token:
- duy nhất:
- Ko trung với các lần generate trước đó
- Người dung login nhiều máy, tại các thời điểm khác nhau -> khac nhau
- Lưu token vào cookie
- Mapping token là của người dùng nào -> lưu token đã được tạo ra vào database -> users (token)
Cơ chế check login như thế nào:
Vào 1 trang bất kỳ (login)
B1) Kiểm tra $_SESSION
- Tồn tại -> login thành công
- Mất session
B2) Kiểm tra token
- Ko có token: Chưa login
- Tồn tại token
- Lấy token từ COOKIE
- Tìm xem token này là của người dùng nào
select * from users where token = '???'
- Thấy tồn tại ban ghi
- Login thành công: lấy thông tin cài $_SESSION -> tăng tốc độ login về sau
- Ko có bản ghi -> token fake (lỗi) -> login failed
Login cho 1 tài khoản người dung có 2 giải pháp:
- Giải pháp hiện tại: Chỉ có thể keep được token cho lần login cuối cùng. Các token của lần login trước đó không được lưu lại
- tokens: Sử dụng cho phép login trên nhiều thiết bị (Keep được token cho từng thiết bị)
- id: tu tang
- user_id -> foreign key
- token -> unique
#utils/utility.php
<?php
function getPost($key, $special = "'") {
$value = '';
if(isset($_POST[$key])) {
$value = $_POST[$key];
//Huy ky tu dac biet trong $value
$value = str_replace($special, "\\".$special, $value);
}
return $value;
}
function getGet($key, $special = "'") {
$value = '';
if(isset($_GET[$key])) {
$value = $_GET[$key];
//Huy ky tu dac biet trong $value
$value = str_replace($special, "\\".$special, $value);
}
return $value;
}
function getMD5Security($pwd) {
return md5(md5($pwd).'SDFKJH8907jgjgs8*(&(87234');
}
function checkLogin() {
if(isset($_SESSION['currentUser']) && $_SESSION['currentUser'] != null) {
//B1) SESSION dang keep login
return true;
}
//B2) Mat ket noi login trong session
if(isset($_COOKIE['token'])) {
$token = $_COOKIE['token'];
$sql = "select * from users where token = '$token'";
$data = executeResult($sql, true);
if($data != null) {
$_SESSION['currentUser'] = $data;
return true;
}
}
return false;
}
function getTimeFormat($str) {
$date = new DateTime($str);
return $date->format('H:i d/m/Y');
}
#db/config.php
<?php
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'gift_db');
const SQL_CREATE_DB = "create database if not exists ".DATABASE;
const SQL_CREATE_TABLE_USER = 'create table if not exists users (
id int primary key auto_increment,
fullname varchar(50),
email varchar(150),
password varchar(32),
token varchar(64)
)';
const SQL_CREATE_TABLE_GIFT = 'create table if not exists gift (
id int primary key auto_increment,
title varchar(150),
thumbnail varchar(500),
content text,
price float,
created_at datetime,
updated_at datetime,
user_id int references users (id)
)';
#db/dbhelper.php
<?php
require_once('config.php');
function init() {
// B1) Ket noi CSDL
$conn = mysqli_connect(HOST, USERNAME, PASSWORD);
mysqli_set_charset($conn, 'utf8');
// B2) Insert du lieu vao database
// echo $sql;die();
// insert, update, delete
mysqli_query($conn, SQL_CREATE_DB);
// B3) Dong ket noi CSDL
mysqli_close($conn);
}
function execute($sql) {
// B1) Ket noi CSDL
$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
mysqli_set_charset($conn, 'utf8');
// B2) Insert du lieu vao database
// echo $sql;die();
// insert, update, delete
mysqli_query($conn, $sql);
// B3) Dong ket noi CSDL
mysqli_close($conn);
}
// array index gom cac phan tu la array key & value
// chi lay 1 phan tu array key & value
function executeResult($sql, $isSingle = false) {
// B1) Ket noi CSDL
$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
mysqli_set_charset($conn, 'utf8');
// B2) Insert du lieu vao database
// echo $sql;die();
// insert, update, delete
$resultset = mysqli_query($conn, $sql);
$data = [];
if($isSingle) {
$data = mysqli_fetch_array($resultset, 1);
} else {
while(($row = mysqli_fetch_array($resultset, 1)) != null) {
$data[] = $row;
}
}
// B3) Dong ket noi CSDL
mysqli_close($conn);
return $data;
}
#gift.php
<?php
session_start();
require_once('utils/utility.php');
require_once('db/dbhelper.php');
if(!checkLogin()) {
header('Location: login.php');
die();
}
$sql = "select * from gift";
$giftList = executeResult($sql);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gift Page</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style type="text/css">
.form-group {
margin-bottom: 20px;
}
.card {
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="container">
<table class="table table-bordered">
<thead>
<tr>
<th>No</th>
<th>Title</th>
<th>Thumbnail</th>
<th>Price</th>
<th>Updated At</th>
</tr>
</thead>
<tbody>
<?php
$index = 0;
foreach($giftList as $item) {
echo '<tr>
<td>'.(++$index).'</td>
<td>'.$item['title'].'</td>
<td><img src="'.$item['thumbnail'].'" style="width: 120px"/></td>
<td>'.number_format($item['price'], 0).'</td>
<td>'.getTimeFormat($item['updated_at']).'</td>
</tr>';
}
?>
</tbody>
</table>
</div>
</body>
</html>
#init.php
<?php
require_once('utils/utility.php');
require_once('db/dbhelper.php');
if(!empty($_POST)) {
//Khoi tao database
init();
execute(SQL_CREATE_TABLE_USER);
execute(SQL_CREATE_TABLE_GIFT);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Init Database</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style type="text/css">
.form-group {
margin-bottom: 20px;
}
.card {
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="container" style="text-align: center;">
<form method="post">
<div class="form-group">
<button class="btn btn-success" style="width: 300px; margin-top: 30px;" name="action" value="init">Init Database</button>
</div>
</form>
</div>
</body>
</html>
#login.php
<?php
session_start();
require_once('utils/utility.php');
require_once('db/dbhelper.php');
if(checkLogin()) {
header('Location: gift.php');
die();
}
$fullname = $email = $pwd = "";
if(!empty($_POST)) {
$email = getPost('email');
$pwd = getPost('pwd');
$pwd = getMD5Security($pwd);
$sql = "select * from users where email = '$email' and password = '$pwd'";
$data = executeResult($sql, true);
if($data == null) {
echo 'Login failed';
} else {
$_SESSION['currentUser'] = $data;
$token = getMD5Security($data['email'].time()).$data['id'];
setcookie('token', $token, time() + 7*24*60*60, '/');
$sql = "update users set token = '$token' where id = ".$data['id'];
execute($sql);
header('Location: gift.php');
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login Page</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style type="text/css">
.form-group {
margin-bottom: 20px;
}
.card {
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="container">
<form method="post">
<div class="form-group">
<label>Email: </label>
<input required type="email" name="email" class="form-control">
</div>
<div class="form-group">
<label>Password: </label>
<input required type="password" name="pwd" class="form-control">
</div>
<div class="form-group">
<p>
<a href="register.php">Create a new account</a>
</p>
<button class="btn btn-success">Login</button>
</div>
</form>
</div>
</body>
</html>
#register.php
<?php
session_start();
require_once('utils/utility.php');
require_once('db/dbhelper.php');
if(checkLogin()) {
header('Location: gift.php');
die();
}
$fullname = $email = $pwd = "";
if(!empty($_POST)) {
$fullname = getPost('fullname');
$email = getPost('email');
$pwd = getPost('pwd');
$pwd = getMD5Security($pwd);
//Kiem tra xem email da ton tai chua
$sql = "select * from users where email = '$email'";
$data = executeResult($sql);
if($data == null || count($data) == 0) {
$sql = "insert into users(fullname, email, password) values ('$fullname', '$email', '$pwd')";
execute($sql);
header('Location: login.php');
} else {
echo 'Email da ton tai';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Register Page</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style type="text/css">
.form-group {
margin-bottom: 20px;
}
.card {
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="container">
<form method="post" onsubmit="return validateData();">
<div class="form-group">
<label>Full Name: </label>
<input required type="text" name="fullname" class="form-control">
</div>
<div class="form-group">
<label>Email: </label>
<input required type="email" name="email" class="form-control">
</div>
<div class="form-group">
<label>Password: </label>
<input required type="password" name="pwd" class="form-control">
</div>
<div class="form-group">
<label>Confirm Password: </label>
<input required type="password" name="confirmPwd" class="form-control">
</div>
<div class="form-group">
<p>
<a href="login.php">I have a account</a>
</p>
<button class="btn btn-success">Save</button>
</div>
</form>
</div>
<script type="text/javascript">
function validateData() {
if($('[name=pwd]').val() != $('[name=confirmPwd]').val()) {
alert('Password does not match')
return false
}
return true
}
</script>
</body>
</html>
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)