By GokiSoft.com|
11:04 10/05/2021|
Học PHP
[Share Code] Tạo web login + đăng ký - kiểm tra trạng thái login bằng cookie - Lập trình PHP/MySQL
#utility.php
<?php
function removeSpecialCharacter($str) {
$str = str_replace('\\', '\\\\', $str);
$str = str_replace('\'', '\\\'', $str);
//$str = abc'okok => abc'okok => abc\'okok
//$str = abc\'okok => abc\\'okok => abc\\\'okok
return $str;
}
function getPost($key) {
//Phan 1: Lay du lieu tu $_POST ($_POST => mang quan ly $key => $value)
$value = '';
if (isset($_POST[$key])) {
$value = $_POST[$key];
}
// return $value;
//Phan 2: Ham xu ly ky tu dac biet
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_PRIVATE_KEY);
}
function checkLogin() {
$token = '';
if (isset($_COOKIE['token'])) {
$token = $_COOKIE['token'];
$sql = "select * from users where token = '$token'";
$user = executeResult($sql, true);
return $user;
}
return null;
}
function signout() {
$token = '';
if (isset($_COOKIE['token'])) {
$token = $_COOKIE['token'];
$sql = "update users set token = null where token = '$token'";
// echo $sql;
execute($sql);
// die();
}
}
#welcome.php
<?php
require_once ('../utils/utility.php');
require_once ('../db/dbhelper.php');
// if (!isset($_COOKIE['status']) || $_COOKIE['status'] != 'login') {
// header('Location: login.php');
// die();
// }
$user = checkLogin();
if ($user == null) {
header('Location: login.php');
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Welcome - 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">Welcome - <?=$user['username']?> (<a href="signout.php">signout</a>)</h2>
</div>
</div>
</div>
</body>
</html>
#signup.php
<?php
require_once ('../utils/utility.php');
require_once ('../db/dbhelper.php');
require_once ('form-signup.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>SignUp - 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">SignUp</h2>
</div>
<div class="panel-body">
<form method="post">
<div class="form-group">
<label for="username">User Name:</label>
<input required="true" type="text" class="form-control" id="username" name="username" 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="password">Password:</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<p>
<a href="login.php">I have a account</a>
</p>
<button class="btn btn-success">Register</button>
</form>
</div>
</div>
</div>
</body>
</html>
#signout.php
<?php
require_once ('../utils/utility.php');
require_once ('../db/dbhelper.php');
signout();
setcookie('status', 'login', time()-7*24*60, '/');
setcookie('token', '', time()-7*24*60, '/');
header('Location: login.php');
#login.php
<?php
require_once ('../utils/utility.php');
require_once ('../db/dbhelper.php');
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</h2>
</div>
<div class="panel-body">
<form method="post">
<div class="form-group">
<label for="username">User Name:</label>
<input required="true" type="text" class="form-control" id="username" name="username" value="">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<p>
<a href="signup.php">Create a new account</a>
</p>
<button class="btn btn-success">Login</button>
</form>
</div>
</div>
</div>
</body>
</html>
#form-signup.php
<?php
// if (isset($_COOKIE['status']) && $_COOKIE['status'] == 'login') {
// header('Location: welcome.php');
// die();
// }
if (checkLogin() != null) {
header('Location: welcome.php');
die();
}
$username = $email = $password = '';
if (!empty($_POST)) {
$username = getPost('username');
$email = getPost('email');
$password = getPost('password');
$password = getMd5Security($password);
if ($username != '' && $email != '' && $password != '') {
$sql = "insert into users(username, email, password) values ('$username', '$email', '$password')";
execute($sql);
header('Location: login.php');
die();
}
}
#form-login.php
<?php
// if (isset($_COOKIE['status']) && $_COOKIE['status'] == 'login') {
// header('Location: welcome.php');
// die();
// }
if (checkLogin() != null) {
header('Location: welcome.php');
die();
}
$username = $password = '';
if (!empty($_POST)) {
$username = getPost('username');
$password = getPost('password');
$password = getMd5Security($password);
if ($username != '' && $password != '') {
$sql = "select * from users where username = '$username' and password = '$password'";
$data = executeResult($sql);
if ($data != null && count($data) > 0) {
$token = $data[0]['username'].time();
$token = getMd5Security($token);
$sql = "update users set token = '$token' where username = '" .$data[0]['username']."'";
execute($sql);
setcookie('status', 'login', time()+7*24*60, '/');
setcookie('token', $token, time()+7*24*60, '/');
header('Location: welcome.php');
die();
}
}
}
#test.php
<?php
//Them cookie
//value: string, boolean, int, number, ...
setcookie('test', 'sdasdasdasdasd', time()+300, '/');
setcookie('a', '1231', time()+300, '/');
setcookie('b', '34324', time()+300, '/');
?>
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>
<body>
<h1>TEST</h1>
</body>
</html>
#readme.txt
- Nội dung kiến thức:
- Cookie
- Điểm chung (Cookie & localStorage)
- Quản lý bởi browser => lưu dữ liệu trên browser
- Khác
- Thời gian sống
- Cách thêm/sửa/xoá cookie nó có hàm khác vs localStorage
- Cookie: mỗi lần gửi yêu cầu lên server -> browser lấy tất cookie (phù hợp) -> gửi lên server: JS (frontend) + Backend (PHP) -> Thao tác và lấy được dữ liệu
- Thêm/sửa/xoá -> cookie -> làm việc được bằng js và php -> nhưng thông thường người ta hay dùng php để thao tác.
- Bảo mật
- Đăng nhập -> biết ai đang đăng nhập
- Mỗi một người login -> sinh ra 1 mã bảo mật riêng.
- Một số lưu ý
- Cookie -> dữ liệu lư ở phía người dùng -> Tuyệt đối ko lưu dữ liệu quan trọng + bảo ko trên cookie
- Nếu dữ thường -> ko quan trong -> share -> lưu cookie bình thường.
- Cơ chế bảo mật login của người:
- login thành công -> token (duy nhất của 1 người dung + ở mỗi thời điểm thì giá trị này khác nhau)
- lưu token vào cookie
- lưu token vào database (session -> thấp)
- lấy token trong cookie -> check trong database -> lấy người dung này ra -> login tự động.
- Các bước: thêm token trong users
===========================================
Mini project:
- signup.php => đăng ký tài khoản người dùng -> đăng nhập thành công -> tự chuyển sang trang welcome.php
- login.php => đăng nhập -> đăng nhập thành công rồi -> welcome.php
- welcome.php -> xem khi người dung đã đăng nhập thành công -> chưa đăng nhập -> tự chuyển sang trang login.php
Phần 1: Kiến thức cũ.
B1. Xây dựng database
create table users (
username varchar(50) primary key,
email varchar(250) not null,
password varchar(32)
)
B2. Phat trien du an
- signup.php
- login.php
- welcome.php
- Build thu vien dung chung cua du
- db
- utility.php
#list.php
<?php
$test = '';
if (isset($_COOKIE['test'])) {
$test = $_COOKIE['test'];
}
echo $test;
#delete.php
<?php
//Them cookie
setcookie('a', '1231', time()-300, '/');
setcookie('b', '34324', time()-300, '/');
?>
<!DOCTYPE html>
<html>
<head>
<title>DELETE</title>
</head>
<body>
<h1>DELETE</h1>
</body>
</html>
#dbhelper.php
<?php
require_once ('config.php');
/**
* 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 ($resultset == null) {
if ($onlyOne) {
return null;
}
return [];
}
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;
}
#config.php
<?php
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'C2010G');
define('MD5_PRIVATE_KEY', 'IdfhhKKodof29*&^8324hjdhfdg2487394sjdfh');
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)