By GokiSoft.com| 16:26 15/05/2021|
Học PHP

[Share Code] Tìm hiểu session trong lập trình PHP - Lập trình PHP/MySQL

SESSION


#Lesson09

##delete_session.php


<?php
session_start();
session_destroy();


##dump.php


<?php
// Code lenh nay dau tien cua chuong - goi 1 lan (require, include)
session_start();

var_dump($_SESSION);


##fake-session.php


<?php
// Code lenh nay dau tien cua chuong - goi 1 lan (require, include)
session_start();

// Bien moi truong $_SESSION -> array: key => value
// Them sua/sua/xoa du lieu -> lam viec nhu array
$_SESSION['fullname'] = 'GokiSoft';
$_SESSION['domain'] = 'https://gokisoft.com';


##readme.txt


- Overview kiến thức
- Kiến thức mới
	- session
	- ajax
- Test 60 phút -> check nhanh kiến thức:

============================================================
Ứng dụng Session trong lưu thông tin đăng nhập

#BT2284

##readme.txt


Mini Project:

Bạn được yêu cầu phát triển dự án như sau

- Phát triển 1 trang init.php thực hiện các chức năng sau.

1) Tạo CSDL đặt tên là bt2284 -> nếu chưa tồn tại

2) Tạo bảng gift nếu chưa tồn tại gồm các column sau: id tự tăng, tiêu đề, thumbnail, nội dung, giá tiền, ngày tạo, ngày sửa, id_user

Bảng user: id tự tăng, tên, email, mật khẩu, token.

- Trang login.php -> sau khi login thành công thì chuyển sang trang quantri.php

- Trang register.php -> sau khi đăng ký thành công thì chuyển sang trang login.php

- quantri.php -> Hiển thị thông tin gift trong database. Cho phép thêm/sửa/xoá -> thực hiện viết phân trang. Chỉ xem khi tài khoản đã login -> và chỉ xem được sản phẩm mình đã thêm vào.

================================================================================
B1. Tao thu vien dung chung cho du an
	- config.php -> cau hinh thong tin database
	- dbhelper.php -> chuc nang xu ly lenh insert, update, delete, select
	- utility.php -> chuc nang tien ich cho PHP
B2. Tao database
- Cach 1: Tao database & tables tren phpmyadmin -> Bai hoc truoc do.
- Cach 2: Xu dung code de tao database & tables

create database if not exists bt2284

create table if not exists users (
	id int primary key auto_increment,
	fullname varchar(50) not null,
	email varchar(200) unique,
	password varchar(32),
	token varchar(32)
)

create table if not exists gift (
	id int primary key auto_increment,
	title varchar(200),
	thumbnail varchar(500),
	content text,
	price float,
	created_at datetime,
	updated_at datetime,
	id_user int references users (id)
)

B3. Phat trien cac chuc nang cua he thong
1) Phat trien cac chuc nang can ban
- register.php
- login.php
- quantri.php

2) Phan quyen nguoi dung:
- 


##db

####config.php


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

define('MD5_PRIMARY_KEY', '8JKjgdfh8237djfh-4)(*3hdfhdfdfjd789234hdfkldfh');


####dbhelper.php


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

/**
* Su dung cho cac lenh: insert, update, delete
*/
function initDB($sql) {
	//Mo ket noi toi database
	$conn = mysqli_connect(HOST, USERNAME, PASSWORD);
	mysqli_set_charset($conn, 'utf8');

	//query
	mysqli_query($conn, $sql);

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

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

	//query
	mysqli_query($conn, $sql);

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

/**
* Su dung cho cac lenh: select
*/
function executeResult($sql, $onlyOne = false) {
	//Mo ket noi toi database
	$conn = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
	mysqli_set_charset($conn, 'utf8');

	//query
	$resultset = mysqli_query($conn, $sql);

	if($onlyOne) {
		$data = mysqli_fetch_array($resultset, 1);
	} else {
		$data = [];
		while(($row = mysqli_fetch_array($resultset, 1)) != null) {
			$data[] = $row;
		}
	}
	//Dong ket noi
	mysqli_close($conn);

	return $data;
}


##utils

####utility.php


<?php
function removeSpecialCharacter($str) {
	$str = str_replace('\\', '\\\\', $str);
	$str = str_replace('\'', '\\\'', $str);
	return $str;
}

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

	return removeSpecialCharacter($value);
}

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

	return removeSpecialCharacter($value);
}

function getMD5Security($pwd) {
	return md5(md5($pwd).MD5_PRIMARY_KEY);
}

function validateToken() {
	if(isset($_SESSION['user'])) {
		// var_dump($_SESSION);
		// echo 'get user from session<br/>';
		return $_SESSION['user'];//memcache
	}

	$token = '';
	if(isset($_COOKIE['token'])) {
		$token = $_COOKIE['token'];

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

		$_SESSION['user'] = $result;

		return $result;
	}

	return false;
}


##init.php


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

$databaseSql = 'create database if not exists '.DATABASE;
initDB($databaseSql);

$userSql = 'create table if not exists users (
				id int primary key auto_increment,
				fullname varchar(50) not null,
				email varchar(200) unique,
				password varchar(32),
				token varchar(32)
			)';
execute($userSql);

$giftSql = 'create table if not exists gift (
				id int primary key auto_increment,
				title varchar(200),
				thumbnail varchar(500),
				content text,
				price float,
				created_at datetime,
				updated_at datetime,
				id_user int references users (id)
			)';
execute($giftSql);
?>
<!DOCTYPE html>
<html>
<head>
	<title>Init database - page</title>
	<meta charset="utf-8">
</head>
<body>
	<h1 style="text-align: center;">Init database & tables successfully!!!</h1>
</body>
</html>


##users

####form-login.php


<?php
if(!empty($_POST)) {
	$email = getPost('email');
	$password = getPost('password');

	$password = getMD5Security($password);

	//check tai khoan co ton tai trong database
	$sql = "select * from users where email = '$email' and password = '$password'";
	$result = executeResult($sql);
	// var_dump($result);
	if($result != null && sizeof($result) == 1) {
		//login thanh cong
		//sinh ra token -> duy nhat cho tung tai khoan nguoi dung + duy nhat tai tung thoi diem login -> bao mat.
		//token -> cookie & database -> verify lai cookie & database -> la nguoi dung nao
		$token = getMD5Security(time().$result[0]['email']);
		setcookie('token', $token, time() + 7*24*60*60, '/');

		$email = $result[0]['email'];
		$sql = "update users set token = '$token' where email = '$email'";
		execute($sql);

		header('Location: ../gift/quantri.php');
		die();
	}
}


####form-register.php


<?php
$fullname = $email = $password = '';
if(!empty($_POST)) {
	$fullname = getPost('fullname');
	$email = getPost('email');
	$password = getPost('password');

	//Kiem tra thanh cong mat khau da khop
	if(!empty($password) && !empty($email)) {
		//Kiem tra username & email <> null -> check bao mat phia server
		//Xem username va email da ton tai trong database
		$sql = "select * from users where email = '$email'";
		$result = executeResult($sql);
		// var_dump($result);
		if($result != null && sizeof($result) > 0) {
			//Tai khoan da ton tai trong database
		} else {
			//Kiem tra moi thong tin da ok -> insert database
			// echo $password.'<br/>';
			$password = getMD5Security($password);
			// echo $password;die();

			$sql = "insert into users(email, fullname, password) values ('$email', '$fullname', '$password')";
			execute($sql);

			header('Location: login.php');
			die();
		}
	}
}


####login.php


<?php
session_start();

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

if(validateToken() != null) {
	header('Location: ../gift/quantri.php');
	die();
}

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

<!DOCTYPE html>
<html>
<head>
	<title>Login - Page</title>
	<meta charset="utf-8">
	<!-- 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</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>
					<p><a href="register.php">Register new user</a></p>
					<button class="btn btn-success">Login</button>
				</form>
			</div>
		</div>
	</div>
</body>
</html>


####logout.php


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

$token = '';
if(isset($_COOKIE['token'])) {
	$token = $_COOKIE['token'];

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

setcookie('token', '', time() - 100, '/');

header('Location: login.php');


####register.php


<?php
session_start();

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

if(validateToken() != null) {
	header('Location: ../gift/quantri.php');
	die();
}

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

<!DOCTYPE html>
<html>
<head>
	<title>Registation Form - Gokisoft</title>
	<meta charset="utf-8">
	<!-- 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>
				<?php
					if(!empty($_POST)) {
						echo '<h2 style="color: red">User is existed</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" value="<?=$fullname?>">
					</div>
					<div class="form-group">
					  <label for="email">Email:</label>
					  <input required="true" type="email" class="form-control" id="email" name="email" value="<?=$email?>">
					</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>
					<p><a href="login.php">I have a account (login)</a></p>
					<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 marching, plz check it again!!!')
				return false
			}

			return true
		})
	})
</script>
</body>
</html>


##gift

####api-gift.php


<?php
session_start();

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

$user = validateToken();
if($user == null) {
	die();
}

$page = getGet('page');
if(empty($page)) {
	$page = 1;
}

$numPage = 2;
$limit = ($page - 1) * $numPage;

$sql = "select gift.*, users.fullname from gift, users where gift.id_user = users.id and gift.id_user = ".$user['id']." order by gift.id asc limit $limit,2";
$dataList = executeResult($sql);

//chuyen array -> json string
echo json_encode($dataList);


####quantri.php


<?php
session_start();

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

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

$sql = "select gift.*, users.fullname from gift, users where gift.id_user = users.id and gift.id_user = ".$user['id']." order by gift.id asc limit 0,2";
$dataList = executeResult($sql);
?>

<!DOCTYPE html>
<html>
<head>
	<title>Gift Page</title>
	<meta charset="utf-8">

	<!-- 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">
		<h1 style="text-align: center;">Hello <font color="red"><?=$user['fullname']?></font> (<a href="../users/logout.php">logout</a>)</h1>
		<table class="table table-bordered">
			<thead>
				<tr>
					<th>No</th>
					<th>Thumbnail</th>
					<th>Title</th>
					<th>Price</th>
					<th>Updated At</th>
					<th>Owner By</th>
					<th style="width: 50px"></th>
					<th style="width: 50px"></th>
				</tr>
			</thead>
			<tbody id="result">
<?php
$count = 0;
foreach ($dataList as $item) {
	echo '<tr>
			<td>'.(++$count).'</td>
			<td><img src="'.$item['thumbnail'].'" style="width: 160px;"/></td>
			<td>'.$item['title'].'</td>
			<td>'.$item['price'].'</td>
			<td>'.$item['updated_at'].'</td>
			<td>'.$item['fullname'].'</td>
			<td><button class="btn btn-warning">Edit</button></td>
			<td><button class="btn btn-danger">Delete</button></td>
		</tr>';
}
?>
			</tbody>
		</table>
		<p style="text-align: center;" id="get-more"><a href="#get-more" onclick="getMore()">View More</a></p>
	</div>
<script type="text/javascript">
	var currentPage = 1;
	var count = 2;

	function getMore() {
		currentPage++
		$.get('api-gift.php?page='+currentPage, function(data) {
			//json
			if(data != null && data != '') {
				arr = JSON.parse(data)
				if(arr.length < 2) {
					$('#get-more').hide()
				}
				console.log(arr)

				for (var i = 0; i < arr.length; i++) {
					item = arr[i]

					$('#result').append(`<tr>
						<td>${++count}</td>
						<td><img src="${item.thumbnail}" style="width: 160px;"></td>
						<td>${item.title}</td>
						<td>${item.price}</td>
						<td>${item.updated_at}</td>
						<td>${item.fullname}</td>
						<td><button class="btn btn-warning">Edit</button></td>
						<td><button class="btn btn-danger">Delete</button></td>
					</tr>`)
				}
			} else {
				$('#get-more').hide()
			}
		})
	}
</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)