By GokiSoft.com| 20:51 11/05/2021|
Học PHP

[Video] Hướng dẫn tìm hiểu cookie - Quản lý xác minh tài khoản login - cookie - Lập trình PHP/MySQL




#utility.php


<?php
function getPwdSecurity($pwd) {
	return md5(md5($pwd).MD5_PRIVATE_KEY);
}

function validateToken() {
	$token = '';

	if (isset($_COOKIE['token'])) {
		$token = $_COOKIE['token'];
		$sql   = "select * from users where token = '$token'";
		$data  = executeResult($sql);
		if ($data != null && count($data) > 0) {
			return $data[0];
		}
	}

	return null;
}

function getGET($key) {
	$value = '';
	if (isset($_GET[$key])) {
		$value = $_GET[$key];
	}
	$value = fixSqlInjection($value);
	return $value;
}

function getPOST($key) {
	$value = '';
	if (isset($_POST[$key])) {
		$value = $_POST[$key];
	}
	$value = fixSqlInjection($value);
	return $value;
}

function fixSqlInjection($str) {
	$str = str_replace("\\", "\\\\", $str);
	$str = str_replace("'", "\'", $str);
	return $str;
}


#users.php


<?php
// if (!isset($_COOKIE['login']) || $_COOKIE['login'] != 'true') {
// 	header('Location: login.php');
// 	die();
// }

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

//Cach 2
$user = validateToken();
if ($user == null) {
	header('Location: login.php');
	die();
}

$sql      = "select * from users";
$userList = executeResult($sql);
?>
<!DOCTYPE html>
<html>
<head>
	<title>Users Page</title>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

	<!-- jQuery library -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

	<!-- Popper JS -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

	<!-- Latest compiled JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
		<div class="panel panel-primary">
			<div class="panel-heading">
				<h2 class="text-center">Users Page - <?=$user['fullname']?>(<a href="logout.php">logout</a>)</h2>
			</div>
			<div class="panel-body">
				<table class="table table-bordered">
					<thead>
						<tr>
							<th>No</th>
							<th>Full Name</th>
							<th>Email</th>
							<th>Birthday</th>
							<th>Address</th>
							<th style="width: 50px;"></th>
							<th style="width: 50px;"></th>
						</tr>
					</thead>
					<tbody>
<?php
$count = 0;
foreach ($userList as $item) {
	echo '<tr>
			<td>'.(++$count).'</td>
			<td>'.$item['fullname'].'</td>
			<td>'.$item['email'].'</td>
			<td>'.$item['birthday'].'</td>
			<td>'.$item['address'].'</td>
			<td><button class="btn btn-warning">Edit</button></td>
			<td><button class="btn btn-danger">Delete</button></td>
		</tr>';
}
?>
					</tbody>
				</table>
			</div>
		</div>
	</div>
</body>
</html>


#register.php


<?php
//Cach 1
// if (isset($_COOKIE['login']) && $_COOKIE['login'] == 'true') {
// 	header('Location: users.php');
// 	die();
// }

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

//Cach 2
$user = validateToken();
if ($user != null) {
	header('Location: users.php');
	die();
}
require_once ('form-register.php');
?>

<!DOCTYPE html>
<html>
<head>
	<title>Registation Page</title>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

	<!-- jQuery library -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

	<!-- Popper JS -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

	<!-- Latest compiled JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
		<div class="panel panel-primary">
			<div class="panel-heading">
				<h2 class="text-center">Registation Page</h2>
			</div>
			<div class="panel-body">
				<form method="post" id="RegisterForm">
					<div class="form-group">
					  <label for="usr">Full Name:</label>
					  <input required="true" type="text" class="form-control" id="usr" name="fullname">
					</div>
					<div class="form-group">
					  <label for="email">Email:</label>
					  <input required="true" type="email" class="form-control" id="email" name="email">
					</div>
					<div class="form-group">
					  <label for="birthday">Birthday:</label>
					  <input required="true" type="date" class="form-control" id="birthday" name="birthday">
					</div>
					<div class="form-group">
					  <label for="pwd">Password:</label>
					  <input required="true" type="password" class="form-control" id="pwd" name="password">
					</div>
					<div class="form-group">
					  <label for="confirmation_pwd">Confirmation Password:</label>
					  <input required="true" type="password" class="form-control" id="confirmation_pwd" name="confirmation_pwd">
					</div>
					<div class="form-group">
					  <label for="address">Address:</label>
					  <input required="true" type="text" class="form-control" id="address" name="address">
					</div>
					<button class="btn btn-success">Register</button>
				</form>
			</div>
		</div>
	</div>
<script type="text/javascript">
	$(function() {
		$('#RegisterForm').submit(function() {
			if($('[name=password]').val() != $('[name=confirmation_pwd]').val()) {
				alert('Password is not matching, plz check it again!!!')
				return false;
			}
			return true;
		})
	})
</script>
</body>
</html>


#logout.php


<?php
//Cach 1
// setcookie('login', 'true', time()-7*24*60*60, '/');

//Cach 2
$token = '';

if (isset($_COOKIE['token'])) {
	require_once ('../db/dbhelper.php');
	require_once ('../utils/utility.php');

	$token = $_COOKIE['token'];
	$sql   = "update users set token = null where token = '$token'";
	execute($sql);
}

setcookie('token', '', time()-7*24*60*60, '/');

header('Location: login.php');


#login.php


<?php
//Cach 1
// if (isset($_COOKIE['login']) && $_COOKIE['login'] == 'true') {
// 	header('Location: users.php');
// 	die();
// }

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

//Cach 2
$user = validateToken();
if ($user != null) {
	header('Location: users.php');
	die();
}

require_once ('form-login.php');
?>

<!DOCTYPE html>
<html>
<head>
	<title>Login Page</title>
	<!-- Latest compiled and minified CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

	<!-- jQuery library -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

	<!-- Popper JS -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

	<!-- Latest compiled JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
		<div class="panel panel-primary">
			<div class="panel-heading">
				<h2 class="text-center">Login Page</h2>
			</div>
			<div class="panel-body">
				<form method="post">
					<div class="form-group">
					  <label for="email">Email:</label>
					  <input required="true" type="email" class="form-control" id="email" name="email">
					</div>
					<div class="form-group">
					  <label for="pwd">Password:</label>
					  <input required="true" type="password" class="form-control" id="pwd" name="password">
					</div>
					<button class="btn btn-success">Login</button>
				</form>
			</div>
		</div>
	</div>
</body>
</html>


#form-register.php


<?php
$fullname = $password = $email = $birthday = $address = '';

if (!empty($_POST)) {
	$fullname = getPOST('fullname');
	$password = getPOST('password');
	$email    = getPOST('email');
	$birthday = getPOST('birthday');
	$address  = getPOST('address');

	if ($fullname != '' && $password != '' && $email != '') {
		//save user into database
		$password = getPwdSecurity($password);

		$sql = "insert into users (fullname, password, email, birthday, address) values ('$fullname', '$password', '$email', '$birthday', '$address')";
		// echo $sql;//SQL Injection
		execute($sql);
		// die();

		//chuyen sang trang login.php
		header('Location: login.php');
		die();
	}
}


#form-login.php


<?php
$password = $email = '';

if (!empty($_POST)) {
	$password = getPOST('password');
	$email    = getPOST('email');

	if ($password != '' && $email != '') {
		//save user into database
		$password = getPwdSecurity($password);

		$sql  = "select * from users where email = '$email' and password = '$password'";
		$data = executeResult($sql);
		if ($data != null && count($data) > 0) {
			//Cach 1: basic
			// setcookie('login', 'true', time()+7*24*60*60, '/');
			//Cach 2: Nang cao
			$token = getPwdSecurity(time().$data[0]['email']);
			setcookie('token', $token, time()+7*24*60*60, '/');

			$sql = "update users set token = '$token' where id = " .$data[0]['id'];
			execute($sql);

			//login thanh cong
			//chuyen sang trang login.php
			header('Location: users.php');
			die();
		}
	}
}


#test-cookie.php


<?php
//Thiết lập 1 cookie -> msg = Hello World
setcookie('msg', 'Hello World', time()+7*24*60*60, '/');
setcookie('status', 'test', time()+7*24*60*60, '/');


#readme.txt


Nội dung kiến thức:
	- Tìm hiểu cookie
	- Ứng dụng cookie trong dự án web
		Mini Project: Quản lý người dùng.
			register.php -> cho phép dky tài khoản người dùng
				- Đky thành công -> login.php
				- Nếu người dùng đã đăng nhập -> users.php
			login.php -> cho phép đăng nhập vào hệ thống
				- Khi người dùng login thành công -> users.php
				- TH người dùng đã login trước đó -> tự đông chuyển sang trang users.php
			users.php -> Hiển thị danh sách người dùng đã đăng ký trong hệ thống.
				- Nếu như người dùng chưa login -> tự chuyển sang trang login.php
====================================================
Mục 1: Tìm hiểu cookie
- Cookie là gì?
- So sanh Cookie & localStorage
	- Điểm chung:
		Cùng lưu trữ và quản lý bởi trình duyệt web
	- Khác biệt:
		Cookie:
			- Thiết lập thời gian tồn tại của cookie đó -> tới hạn -> trình duyệt web sẽ tự động xoá dữ liệu đó đi.
			- Cookie: thêm/sửa/xoá bằng js (frontend) hoặc từ phía server - backend (PHP)
			- Khi gửi yêu cầu lên server (request URL) -> gửi toàn bộ cookie tương ứng (phù hợp) -> gửi kèm lên server -> đọc được nội dung của cookie.
Mục 2: Ứng dụng -> Mini Project
B1. Xay dung database
create table users (
	id int primary key auto_increment,
	fullname varchar(50) not null,
	email varchar(150),
	birthday date,
	password varchar(32),
	address varchar(200)
)

B2. Phat trien du an
- Build thu vien su dung chung cho du an
	- config.php
	- dbhelper.php
	- utility.php
- Xay dung page
	- register.php
	- login.php
	- users.php
- Phat trien them cac chuc nang theo yeu cau.
(document.cookie = 'login=true;path=/')
- Yeu quan ly login tren he thong website:
	- Xac dinh duoc tai khoan nao dang dang nhap vao he thong
	- Quan ly duoc trang thai dang nhap cua tai khoan do
	- Dam bao duoc tinh nang bao mat -> rat kho hack
- Giai phap:
	- Login thanh cong -> token (cookie) -> value (token) khac nhau voi tung tai khoan nguoi dung & khac nhau tai tung thoi diem login
	- token (value) -> xac thuc dc token hop le khong -> tuong ung vs tai khoan nguoi dung nao
	-> Yeu cau: luu token do vao trong database

	alter table users
	add token varchar(32)

	


#list-cookie.php


<?php
// var_dump($_COOKIE);

$status = $msg = '';

if (isset($_COOKIE['status'])) {
	$status = $_COOKIE['status'];
}
if (isset($_COOKIE['msg'])) {
	$msg = $_COOKIE['msg'];
}

echo $msg.'-'.$status;

foreach ($_COOKIE as $key => $value) {
	echo '<br/>'.$key.'-'.$value;
}


#delete-cookie.php


<?php
setcookie('status', 'test', time()-10, '/');


#dbhelper.php


<?php
require_once ('config.php');

/**
 * Su dung cho lenh: insert/update/delete
 */
function execute($sql) {
	// Them du lieu vao database
	//B1. Mo ket noi toi database
	$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
	mysqli_set_charset($conn, 'utf8');

	//B2. Thuc hien truy van insert
	mysqli_query($conn, $sql);

	//B3. Dong ket noi database
	mysqli_close($conn);
}
/**
 * Su dung cho lenh: select
 */
function executeResult($sql) {
	// Them du lieu vao database
	//B1. Mo ket noi toi database
	$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
	mysqli_set_charset($conn, 'utf8');

	//B2. Thuc hien truy van insert
	$resultset = mysqli_query($conn, $sql);
	$data      = [];

	while (($row = mysqli_fetch_array($resultset, 1)) != null) {
		$data[] = $row;
	}

	//B3. Dong ket noi database
	mysqli_close($conn);

	return $data;
}


#config.php


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

define('MD5_PRIVATE_KEY', '09JJJjhh7834jHJG876312^&%shjdgsjagdasKoks');


Tags:

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)