---
# System prepended metadata

title: 'Trang web có chức năng register, login sử dụng PHP, MySQL'

---

**Trang web có chức năng register, login sử dụng PHP, MySQL**

# File users.sql
Tạo database login_register và tạo bảng users trên phpmyadmin, tiếp theo xuất file **users.sql**
```
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `full_name` varchar(100) NOT NULL,
  `email` varchar(200) NOT NULL,
  `password` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;
```

![Screenshot (1).png](https://hackmd.io/_uploads/SkwMJVH76.png)

# File database.php
Tạo file kết nối database **database.php**
```
<?php
    $hostName = "localhost";
    $dbUser = "root";
    $dbPass = "";
    $dbName = "login_register";
    $conn = mysqli_connect($hostName, $dbUser, $dbPass, $dbName);
    if (!$conn)
    {
        die("Something went wrong!");
    }
?>
```

# File registration.php
```
<?php
    session_start();
    if (isset($_SESSION["user"]))
    {
        header("Location: login.php");
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registration Form</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <?php
            if (isset($_POST["submit"]))
            {
                $fullName = $_POST["fullname"];
                $email = $_POST["email"];
                $password = $_POST["password"];
                $passwordRepeat = $_POST["repeat_password"];

                $passwordHash = password_hash($password, PASSWORD_DEFAULT);

                $errors = array();

                if (empty($fullName) || empty($email) || empty($password) || empty($passwordRepeat))
                {
                    array_push($errors,"Please complete all information.");
                };
                if (!filter_var($email, FILTER_VALIDATE_EMAIL))
                {
                    array_push($errors,"Email is not valid.");
                };
                if (strlen($password) < 8)
                {
                    array_push($errors,"Password must be at least 8 characters long.");
                };
                if ($password != $passwordRepeat)
                {
                    array_push($errors,"Please verify your password.");
                };

                require_once "database.php";
                $sql = "SELECT * FROM users WHERE email = '$email'";
                $result = mysqli_query($conn, $sql);
                $rowCount = mysqli_num_rows($result);
                if ($rowCount > 0)
                {
                    array_push($errors,"Email already exists!");
                }
                if (count($errors) > 0)
                {
                    foreach ($errors as $error)
                    {
                        echo "<div class='alert alert-danger'>$error</div>";
                    }
                }
                else
                {
                    $sql = "INSERT INTO users (full_name, email, password) VALUES (?, ?, ?)";
                    $stmt = mysqli_stmt_init($conn);
                    $prepareStmt = mysqli_stmt_prepare($stmt, $sql);
                    if ($prepareStmt)
                    {
                        mysqli_stmt_bind_param($stmt,"sss", $fullName, $email, $passwordHash);
                        mysqli_stmt_execute($stmt);
                        echo "<div class='alert alert-success'>Successfully registered account!</div>";
                    }
                    else
                    {
                        die("Something went wrong!");
                    }
                };
            }
        ?>
        <form action="registration.php" method="POST">
            <div class="form-group">
                <input type="text" class="form-control" name="fullname" placeholder="Full Name: ">
            </div>
            <div class="form-group">
                <input type="email" class="form-control" name="email" placeholder="Email: ">
            </div>
            <div class="form-group">
                <input type="password" class="form-control" name="password" placeholder="Password: ">
            </div>
            <div class="form-group">
                <input type="password" class="form-control" name="repeat_password" placeholder="Repeat Password: ">
            </div>
            <div class="form-btn">
                <input type="submit" class="btn btn-primary" value="Register" name="submit">
            </div>
        </form>
        <div><p>Already Registed. <a href="login.php">Login Here</a></p></div>
    </div>
</body>
</html>
```

# File style.css
```
.container {
    max-width: 600px;
    margin: 0 auto;
    padding: 50px;
    box-shadow: rgba(144, 194, 235, 0.2) 0px 7px 29px 0px;
}

.form-group {
    margin-bottom: 30px;
}
```

![Screenshot (13).png](https://hackmd.io/_uploads/Syqv-4rQp.png)

![Screenshot (14).png](https://hackmd.io/_uploads/Bk69-ES7T.png)

![Screenshot (15).png](https://hackmd.io/_uploads/Bk22bVrm6.png)

![Screenshot (16).png](https://hackmd.io/_uploads/SydyM4SQT.png)

# File login.php
```
<?php
    session_start();
    if (isset($_SESSION["user"]))
    {
        header("Location: login.php");
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Form</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <?php
            if (isset($_POST["login"])) 
            {
                $email = $_POST["email"];
                $password = $_POST["password"];
                require_once "database.php";
                $sql = "SELECT * FROM users WHERE email = '$email'";
                $result = mysqli_query($conn, $sql);
                $user = mysqli_fetch_array($result, MYSQLI_ASSOC);
                if ($user)
                {
                    if (password_verify($password, $user["password"]))
                    {
                        session_start();
                        $_SESSION["user"] = "yes";
                        header("Location: index.php");
                        die();
                    }
                    else
                    {
                        echo "<div class='alert alert-danger'>Password does not match!</div>";
                    }
                }
                else
                {
                    echo "<div class='alert alert-danger'>Email does not match!</div>";
                }
            }
        ?>
        <form action="login.php" method="POST">
            <div class="form-group">
                <input type="email" placeholder="Enter Email:" name="email" class="form-control">
            </div>
            <div class="form-group">
                <input type="password" placeholder="Enter Password:" name="password" class="form-control">
            </div>
            <div class="form-btn">
                <input type="submit" value="Login" name="login" class="btn btn-primary">
            </div>
        </form>
        <div><p>Not Registed Yet. <a href="registration.php">Register Here</a></p></div>
    </div>
</body>
</html>
```

![Screenshot (17).png](https://hackmd.io/_uploads/BJPFGVHXT.png)

![Screenshot (18).png](https://hackmd.io/_uploads/BJiof4HXa.png)

![Screenshot (19).png](https://hackmd.io/_uploads/SJ8Zm4HX6.png)

# File index.php
```
<?php
    session_start();
    if (!isset($_SESSION["user"]))
    {
        header("Location: login.php");
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Dashboard</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <h1>Welcome To Dashboard</h1>
        <a href="logout.php" class="btn btn-warning">Logout</a>
    </div>
</body>
</html>
```

# File logout.php
```
<?php
    session_start();
    session_destroy();
    header("Location: login.php");
?>
```

![Screenshot (20).png](https://hackmd.io/_uploads/SkWhmErmT.png)


