By GokiSoft.com| 20:35 28/11/2022|
Học PHP

[Source Code] Tìm hiểu session & ứng dụng trong dự án Authentication - C2206L

#config.php

<?php
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DB', 'C2206L');

#dbhelper.php

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

function query($sql) {
	//B1. Mo ket noi toi CSDL
	$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DB);
	mysqli_set_charset($conn, 'utf8');

	//B2. Them/sua/xoa/lay du lieu tu database -> insert/update/delete/select
	mysqli_query($conn, $sql);

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

function queryResult($sql, $isSingle = false) {
	//B1. Mo ket noi toi CSDL
	$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DB);
	mysqli_set_charset($conn, 'utf8');

	//B2. Them/sua/xoa/lay du lieu tu database -> insert/update/delete/select
	$resultset = mysqli_query($conn, $sql);
	$data = [];

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

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

	if($isSingle) {
		if(count($data) == 0) return null;

		return $data[0];
	}
	return $data;
}

function getSecurityMD5($str) {
	//Ma nay go tuy y -> go sao cung dc.
	$PRIVATE_KEY = '87346jGJGs23&^%&^sdfgh24jgjhsgdf';
	return md5(md5($str).$PRIVATE_KEY);
}

function checkToken() {
	if(!isset($_COOKIE['token'])) return null;

	$token = $_COOKIE['token'];
	$sql = "select * from students where token = '$token'";
	$data = queryResult($sql, true);

	return $data;
}

#login.php

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

$std = checkToken();
if($std != null) {
	header('Location: show.php');
	die();
}

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

	$password = getSecurityMD5($password);

	$sql = "select * from students where email = '$email' and password = '$password'";
	$std = queryResult($sql, true);

	if($std != null) {
		//B1. Gen token
		$token = $std['id'].'#'.time().'#'.getSecurityMD5($std['email'].time());

		//B2. Luu cookie phía người dùng
		setcookie('token', $token, time() + 30 * 24 * 60 * 60, '/');

		//B3. Luu vao database
		$sql = "update students set token = '$token' where id = ".$std['id'];
		query($sql);

		header('Location: show.php');
		die();
	}
}
?>

<!DOCTYPE html>
<html>
<head>
	<title>Register - 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">Register</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" value="">
					</div>
					<div class="form-group">
					  <label for="password">Password:</label>
					  <input required="true" type="password" class="form-control" id="password" name="password" value="">
					</div>
					<p>
						<a href="register.php">Create a new account</a>
					</p>
					<button type="submit" class="btn btn-success">Login</button>
				</form>
			</div>
		</div>
	</div>
</body>
</html>

#readme.txt

Nội dung kiến thức:
	- Session trong PHP
	- Ứng dụng Cookie/Session/CSDL trong Authentication
		Mini Project: 
			Nguyen tac luu password:
				- Ko duoc luu mat khau tho
				- Ma hoa du lieu -> ma hoa 1 chieu
				bcrypt
					A -> A1
					  -> A2
					  -> A3
					  ...

					bruce force -> hack password -> table hash (vbuletin, phpbb -> md5)
			Login
				- Khi chưa login
				- Login thành công -> CHuyển sang trang Hiển thị danh sách người dùng
			Register
				- Khi chưa register
				- Login thành công -> CHuyển sang trang Hiển thị danh sách người dùng

			Hiển thị danh sách người -> Chỉ khi login thành công mới xem được
									 -> Chưa login -> Login.php
=======================================================================================
Mong muốn:
	Student: token -> varchar(32)

	Login.php
		- Kiểm tra nếu chưa login
			- Nhập dữ liệu Form
				- Kiểm tra thông
					- Đúng
						- gen token -> tính duy nhất (theo tài khoản, theo thời điểm)
						- Gửi token về client -> trình duyệt web
						- Lưu token vào student (token) -> Cho sinh viên tương ứng
					- Sai
						- Login.php
		- Đã login
			- Check login auto
				- Client -> server -> doc token (cookie) -> truy van trong database -> tuong ung vs ngươi dùng nào
					- Tộn tại bản ghi -> login tự động thành công
					- Ngược -> FAILED
			- show.php
			

#register.php

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

$std = checkToken();
if($std != null) {
	header('Location: show.php');
	die();
}

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

	$password = getSecurityMD5($password);

	//B2. Them/sua/xoa/lay du lieu tu database -> insert/update/delete/select
	$sql = "insert into students(fullname, email, birthday, address, password) values ('$fullname', '$email', '$birthday', '$address', '$password')";
	query($sql);
}
?>

<!DOCTYPE html>
<html>
<head>
	<title>Register - 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">Register</h2>
			</div>
			<div class="panel-body">
				<form method="post">
					<div class="form-group">
					  <label for="usr">Name:</label>
					  <input required="true" type="text" class="form-control" id="usr" name="fullname" value="">
					</div>
					<div class="form-group">
					  <label for="email">Email:</label>
					  <input required="true" type="email" class="form-control" id="email" name="email" value="">
					</div>
					<div class="form-group">
					  <label for="birthday">Birthday:</label>
					  <input type="date" class="form-control" id="birthday" name="birthday" value="">
					</div>
					<div class="form-group">
					  <label for="address">Address:</label>
					  <input type="text" class="form-control" id="address" name="address" value="">
					</div>
					<div class="form-group">
					  <label for="password">Password:</label>
					  <input required="true" type="password" class="form-control" id="password" name="password" value="">
					</div>
					<!-- <div class="form-group">
					  <label for="confirmPwd">Confirm Pwd:</label>
					  <input type="password" class="form-control" id="confirmPwd" name="confirmPwd" value="">
					</div> -->
					<p>
						<a href="login.php">I have a account</a>
					</p>
					<button type="submit" class="btn btn-success">Register</button>
				</form>
			</div>
		</div>
	</div>
</body>
</html>

#show.php

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

$std = checkToken();
if($std == null) {
	header('Location: login.php');
	die();
}

$sql = "select * from students";
$data = queryResult($sql);
?>

<!DOCTYPE html>
<html>
<head>
	<title>Show student - 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">
		<a href="add.php"><button class="btn btn-success mb-2 mt-2">Add new student</button></a>
		<div class="panel panel-primary">
			<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: 190px"></th>
						</tr>
					</thead>
					<tbody>
<?php
$count = 0;
foreach ($data as $item) {
	echo '<tr>
			<td>'.++$count.'</td>
			<td>'.$item['fullname'].'</td>
			<td>'.$item['email'].'</td>
			<td>'.$item['birthday'].'</td>
			<td>'.$item['address'].'</td>
			<td>
				<a href="edit.php?id='.$item['id'].'"><button class="btn btn-warning">Edit</button></a>
				<a href="delete.php?id='.$item['id'].'"><button class="btn btn-danger">Remove</button></a>
			</td>
		</tr>';
}
?>
					</tbody>
				</table>
			</div>
		</div>
	</div>
</body>
</html>

#test.php

<?php
session_start();

var_dump($_SESSION);

#vidu.php

<?php
session_start();

// var_dump($_SESSION);

//Them du lieu vao session
$_SESSION['abc'] = 'TRAN VAN A';

//Xoa du lieu khoi session
// unset($_SESSION['abc']);

//Sua thong tin
// $_SESSION['abc'] = '123';

// session_destroy();

echo 'Setup data';
Tags:

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

5

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