By GokiSoft.com| 14:33 16/05/2021|
Học PHP

[Share Code] Tìm hiểu về session + ajax trong lập trình PHP - Lập trinh



#readme.txt


Nội dung kiến thức
	- session
		- Là gì???
		- Tìm hiểu cách quản lý bộ nhớ session trên server
			- Làm sao nó có thể phân biệt được bộ nhớ session của client nào
		- Ứng dụng trong thực tiền
	- ajax
		- Chu y:
	- OOP -> class object trong PHP
======================================================


#delete-session.php


<?php
session_start();


#dump.php


<?php
session_start();

var_dump($_SESSION);


#test-oop.php


<?php
//Quan ly thong tin cua Sinh Vien, Dong Vat, Xe Co -> co nhung giap gi de lam.

class Student {
	var $fullname;
	var $email;
	var $address;

	public function running() {
		echo "<br/>running ... ".$this->fullname;
	}
}

$std = new Student();
$std->fullname = 'TRAN VAN A';
$std->email = 'tranvana@gmail.com';

echo $std->fullname;
$std->running();

$std2 = new Student();
$std2->fullname = "OKOK";
echo "<br/>".$std2->fullname;
$std2->running();


#test-session.php


<?php
session_start();

// $_SESSION -> mang quan ly du lieu theo key => value ($_GET, $_POST, $_REQUEST, $_COOKIE) => array: key => value
// Them, sua, xoa du lieu trong $_SESSION => nhu bai hoc ve array key => value
// Them du lieu vao trong $_SESSION nhu sau
$_SESSION['fullname'] = 'TRAN VAN A';
$_SESSION['domain'] = 'gokisoft.com';
$_SESSION['time'] = date('H:i:s d/m/Y');


#config.php


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

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


#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;
}


#utility.php


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

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

	$token = '';

	if (isset($_COOKIE['token'])) {
		$token = $_COOKIE['token'];
		$sql   = "select * from users where token = '$token'";
		$data  = executeResult($sql);
		if ($data != null && count($data) > 0) {
			$_SESSION['user'] = $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;
}


#api-users.php


<?php
session_start();

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

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

$page = getGet('page');
$numPage = 3;
$limit = ($page - 1) * $numPage;
$sql      = "select id, fullname, email, birthday, address from users limit $limit, 3";
$userList = executeResult($sql);

echo json_encode($userList);

// $count = $limit + 1;
// 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>';
// }


#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();
		}
	}
}


#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();
	}
}


#login.php


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

$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>


#register.php


<?php
session_start();
//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>


#users.php


<?php
session_start();
// 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 limit 0, 3";
$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 id="result">
<?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>
				<p style="text-align: center;">
					<a href="#load-more" onclick="loadMore(this)">Load More</a>
				</p>
			</div>
		</div>
	</div>

<script type="text/javascript">
	var currentPage = 1;
	var count = 3;

	function loadMore(that) {
		currentPage++
		$.get('api-users.php?page='+currentPage, function(data) {
			if(data == null || data == '') {
				$(that).parent().hide()
			} else {
				userList = JSON.parse(data)
				if(userList.length < 3) {
					$(that).parent().hide()
				}
				for (var i = 0; i < userList.length; i++) {
					$('#result').append(`<tr>
								<td>${++count}</td>
								<td>${userList[i]['fullname']}</td>
								<td>${userList[i]['email']}</td>
								<td>${userList[i]['birthday']}</td>
								<td>${userList[i]['address']}</td>
								<td><button class="btn btn-warning">Edit</button></td>
								<td><button class="btn btn-danger">Delete</button></td>
							</tr>`)
				}
			}
			// $('#result').append(data)
		})
	}
</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)