By GokiSoft.com| 14:54 25/04/2022|
Học PHP

[Video] Bài tập - Tạo website bán hàng lư niệm - Login - Lập trình PHP/MySQL - C2110I

Bài tập - Tạo website bán hàng lư niệm - Login - Lập trình PHP/MySQL


#readme.txt


Tổ chức dự án:
- db:
	- config.php
	- dbhelper.php
- utils
	- utility.php
- init.php -> Sử dụng tạo CSDL + tables
- login.php
- register.php
- gift.php -> Hiển thị danh sách sản phầm quà tặng trong dự án

B1) Dang ky tai -> email ko duoc trung
	- B1) Sua lai thiet ke database
	- B2) Sua code -> verify duplicate email

B2) Authentication
	- Neu chua login -> se chi vao dc trang login.php & register.php
	- Neu da login -> se chi vao dc trang gift.php

Solution 1:
	- Login.php -> thanh cong -> luu thong tin login vao Session

Solution 2:
	- Login.php -> dien thong tin dang nhap
		-> TH1: failed
		-> TH2: success
			- Luu thong tin xuong session -> keep login & verify nhanh
			- Gen token: duy nhat
				- Duy nhat vs tung nguoi dung o tung thoi diem login khac nhau
				- Token login khac nhau tai thoi diem khac nhau ...
			- Luu thong tin token vao cookie
			- Luu thong tin token vao database
				so sanh token gui tu client len server cookie & mapping vs token cua tk nao -> Tim ra dc nguoi dung tuong ung
	- Thread login hoat dong nhu the nao?
		- Khi nguoi dung truy cap vao website
			- Kiem tra trong Session
				- Session ton tai cUser -> login thanh cong -> verify nhanh
				- Session ko ton tai
					- Lay token tu cookie
						Token ton tai
							- Tim kiem token trong database -> xem mapping vs tk nguoi dung naof
								select * from users where token = 'token cookie'
								- Tim thay trong users
									- Luu thong tin nguoi dung Session -> login lan sau nhanh hon
								- TH ko tim thay:
									token sai | fake
						Token ko ton tai -> chua login


#utils/utility.php


<?php
// Viet cau truy van theo cau truc: $sql = "???";
function getPost($key) {
	$value = '';

	if(isset($_POST[$key])) {
		$value = $_POST[$key];
		$value = str_replace("'", "\\'", $value);
	}

	return $value;
}

// Viet cau truy van theo cau truc: $sql = "???";
function getGet($key) {
	$value = '';

	if(isset($_GET[$key])) {
		$value = $_GET[$key];
		$value = str_replace("'", "\\'", $value);
	}

	return $value;
}


function getMD5Security($pwd) {
	return md5(md5($pwd).'jhgJHGsdy^&%723GJ67532GHFd');
}

function getTimeFormat($str) {
	$mydate = new DateTime($str);
	return $mydate->format('H:i d/m/Y');
}

function checkLogin() {
	if(isset($_SESSION['cUser'])) {
		//Session ton tai
		return true;
	}
	if(isset($_COOKIE['token'])) {
		$token = $_COOKIE['token'];

		$sql = "select * from users where token = '$token'";
		$data = executeResult($sql, true);

		if($data != null) {
			$_SESSION['cUser'] = $data;
			return true;
		}
	}

	return false;
}


#db/config.php


<?php
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'gift_db');

const SQL_CREATE_DATABASE = '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(250),
			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) Tao ket noi toi CSDL
	$conn = mysqli_connect(HOST, USERNAME, PASSWORD);
	mysqli_set_charset($conn, 'utf8');

	// B2) Thuc hien cau insert into
	// echo $sql;
	// die();
	// insert, update, delete
	mysqli_query($conn, SQL_CREATE_DATABASE);

	// B3) Dong ket noi
	mysqli_close($conn);
}

function execute($sql) {
	// B1) Tao ket noi toi CSDL
	$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
	mysqli_set_charset($conn, 'utf8');

	// B2) Thuc hien cau insert into
	// echo $sql;
	// die();
	// insert, update, delete
	mysqli_query($conn, $sql);

	// B3) Dong ket noi
	mysqli_close($conn);
}

function executeResult($sql, $isSingle = false) {
	// B1) Tao ket noi toi CSDL
	$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
	mysqli_set_charset($conn, 'utf8');

	// B2) Thuc hien cau insert into
	$resultset = mysqli_query($conn, $sql);

	$data = null;

	if($isSingle) {
		$data = mysqli_fetch_array($resultset, 1);
	} else {
		$data = [];
		while(($row = mysqli_fetch_array($resultset, 1)) != null) {
			$data[] = $row; //$row -> array key & value
		}
	}
	
	// B3) Dong ket noi
	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
session_start();

require_once('utils/utility.php');
require_once('db/dbhelper.php');

if(!checkLogin()) {
	header('Location: login.php');
	die();
}

if(!empty($_POST)) {
	//Khoi tao database
	init();

	//Khoi tao tables
	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">
		<button class="btn btn-lg btn-info" style="width: 300px; margin-top: 50px;" name="action" value="init">Init Database</button>
	</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();
}

$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) {
		//Dang nhap thanh cong
		//Luu xuong session
		$_SESSION['cUser'] = $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');
		die();
	} else {
		//Login failed
	}
}
?>
<!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">
			<p>
				<a href="register.php">Create a new account</a>
			</p>
		</div>
		<div class="form-group">
			<button class="btn btn-success">Login</button>
			<a href="list.php"><button type="button" class="btn btn-secondary">Back</button></a>
		</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(count($data) == 0) {
		$sql = "insert into users(fullname, email, password) values ('$fullname', '$email', '$pwd')";
		execute($sql);

		header('Location: login.php');
		die();
	} 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">
			<p>
				<a href="login.php">I have a account</a>
			</p>
		</div>
		<div class="form-group">
			<button class="btn btn-success">Save</button>
			<a href="list.php"><button type="button" class="btn btn-secondary">Back</button></a>
		</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)

Đăng nhập để làm bài kiểm tra

Chưa có kết quả nào trước đó