이 블로그 검색

레이블이 PHP인 게시물을 표시합니다. 모든 게시물 표시
레이블이 PHP인 게시물을 표시합니다. 모든 게시물 표시

2023년 4월 16일 일요일

Creating a Login Authentication Website with APM (Apache2, PHP, MySQL)

Purpose

Create a website with APM (Apache2, Php, Mysql) authentication using PHP's built-in session feature.

  1. Implement login function
  2. Implement main page
    • Only accessible after logging in
    • Show who is currently logged in
  3. Implement logout function
  4. Implement sign-up function
    • Check for duplicate IDs
    • Check for empty fields

The session ID is the user ID.

*Note:

Setting up APM (Apache, PHP, MySQL) Environment on Ubuntu

Set up the Database(MySQL)

Server name = "localhost"

Database name = "test"

Database User name = "root"

Database Password= "1234"

Table name= “users”

first row of table for admin ID: admin

first row of table for admin PWD: admin

Steps

  1. Create a database with the MySQL user:

    mysqladmin -u root create test -p
    
  2. Connect to MySQL user:

    mysql -u root -p
    
  3. Set the root account password (if not already set):

    use mysql;
    ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '1234';
    
  4. Select the database to use:

    use test;
    
  5. Create a table:

    create table users(
    	id int primary key auto_increment,
    	user_id varchar(255),
    	user_pwd varchar(255)
    );
    
  6. Insert a default admin account into the table:

    insert into users (user_id, user_pwd) values ('admin','admin');
    
  7. Verify the data in the table:

    select * from users;
    
  8. Exit the MySQL user:

    quit;
    
  9. Start the MySQL server:

    service mysql start
    
  10. Start the Apache server:

    # Start Apache
    sudo service apache2 start
    # Stop Apache
    sudo service apache2 stop
    # Restart Apache
    sudo service apache2 restart
    

Code

Main.php

<?php
session_start(); // Start session

if(!isset($_SESSION['user_id'])) // If not logged in
{
    header ('Location: ./login.html'); // Redirect to login page
}

echo "<h2>Login Success</h2><br><h2>";
echo $_SESSION['user_id'];
echo ", you have successfully logged in.</h2><br><br>"; // Print user's name
echo "<a href=logout.php>Logout</a>"; // Print logout link

?>

login.html

<html>
<head>
    <title>Login Page</title>
    <meta charset="utf-8">
</head>
<body>
    <form method="post" action="/login_chk.php">
        <div>
            <label for="user_id">ID </label>
            <input type="text" name="user_id"/>
        </div>
        <div>
            <label for="user_pwd">Password </label>
            <input type="text" name="user_pwd"/>
        </div>

        <div class="button">
            <button type="submit">Login</button>
        </div>
    </form>
    <button onclick="location.href='sign_up.html'">Sign Up</button>
</body>
</html>

login_chk.php

<?php
session_start(); // Start session

$id = $_POST['user_id']; // User ID
$pw = $_POST['user_pwd']; // Password

$servername = "localhost"; // Server name
$username = "root"; // User name
$password = "1234"; // Password
$dbname = "test"; // Database name

// Connect to database
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get user info with the entered ID
$sql = "SELECT * FROM users WHERE user_id='$id'";
$result = $conn->query($sql);

// If user info exists
if($result->num_rows == 1){
    $row = $result->fetch_array(MYSQLI_ASSOC);
    // If the entered password is correct
    if($row['user_pwd'] == $pw){
        $_SESSION['user_id'] = $id;
        // If session is successfully saved
        if(isset($_SESSION['user_id'])){
            header('Location: ./Main.php');
        }
        else{
            echo "Session save failed";
        }
    }
    // If the entered password is incorrect
    else{
        echo "Wrong ID or password.";
        header('Location: ./login.html');
    }
}
// If user info does not exist
else{
    echo "Wrong ID or password.";
    header('Location: ./login.html');
}

$conn->close(); // Close database connection
?>

sign_up.html

<html>
<head>
    <title> Sign Up </title>
    <meta charset="utf-8">
</head>
<body>
    <form action = "./sign_up.php" method="post">
        <div>
            <label for="user_id"> ID </label>
            <input type="text" name="user_id"/>
        </div>
        <div>
            <label for="user_pwd"> PW </label>
            <input type="text" name="user_pwd"/>
        </div>

        <div class="button">
            <input type="submit" value="submit">
        </div>
    </form>
</body>
</html>

sign_up.php

<?php
$id = $_POST['user_id']; // ID submitted by the user
$pw = $_POST['user_pwd']; // Password submitted by the user

if($id==NULL || $pw==NULL) // If the user didn't fill out all the fields
{
    echo "Please fill out all the fields";
    echo "<a href=sign_up.html>back page</a>";
    exit();
}

$servername = "localhost"; // Server name
$username = "root"; // User name
$password = "1234"; // Password
$dbname = "test"; // Database name

// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// If the ID already exists
$sql = "SELECT * FROM users WHERE user_id='$id'";
$result = $conn->query($sql);

if($result->num_rows == 1)
{
    echo "ID already exists";
    echo "<a href=sign_up.html>back page</a>";
    exit();
}

// Add new user info to the database
$sql = "INSERT INTO users (user_id, user_pwd) VALUES ('$id', '$pw')";
$signup = mysqli_query($conn, $sql);

// If the signup process is successful
if($signup)
{
    echo "Registration completed.";
}

$conn->close(); // Close the database connection
?>

logout.php

<?php
session_start(); // Start the session

$res = session_destroy(); // Remove all session variables

if($res)
{
    header('Location: ./Main.php'); // If the logout process is successful, redirect to the login page
}
?>

2023년 4월 11일 화요일

Setting up APM (Apache, PHP, MySQL) Environment on Ubuntu

 

System Specification

Name Version
VirtualBox 7.0
Ubuntu 22.04.2
Windows 11
CPU AMD Ryzen 7 5700U
RAM 16.0 GB
GPU -
SDD 512 GB

Installing Apache2

  1. Open the Ubuntu terminal and enter the following command. If asked if you really want to install, type y and press Enter.

    # Install apache2
    sudo apt install apache2
    
  2. Enter the server start command to check if the Apache server is installed correctly.

    # Start Apache server
    sudo service apache2 start
    # Stop Apache server
    sudo service apache2 stop
    # Restart Apache server
    sudo service apache2 restart
    
  3. Open a web browser and go to http://localhost to check if the server is running.

Installing Mysql

  1. Open the Ubuntu terminal and enter the following command. If asked if you really want to install, type y and press Enter.

    # Install Mysql
    sudo apt install mysql-server
    
  2. Check the mysql version to make sure it is installed correctly.

    # Check mysql version
    mysql --version
    

Installing PHP

  1. Open the Ubuntu terminal and enter the following command. If asked if you really want to install, type y and press Enter.

    # Install PHP and modules that allow php to use apache2 and mysql
    sudo apt install php libapache2-mod-php php-mysq
    
  2. Use the following command to check if it is installed correctly

    # Check php version
    php -v
    

Testing the server

In order to test if the server is working properly, let's create a php file and test it on the Apache server.

To do this, you need to know basic Linux commands and how to use vim.

vim

The most basic text editor in Linux. Similar to Windows' Notepad.

  • In the past, vi was used, but vim was created by adding some more features to it.
  • Vim is a text editor that is designed to edit text without using a mouse by default, so it is very difficult to use without knowing the shortcuts and how to use it.
  • Depending on the Linux version and type, vim may not be installed.

Necessary Linux commands

bashCopy code
sudo su # Switch to Linux root account. Has the highest privileges of all Linux accounts
cd / # cd is used to move, and adding / moves to the highest-level folder
cd .. # Adds .. to move to the parent folder
ls # Shows the file and folder list of the current directory
vim # Creates or opens a vim file when followed by a file

Necessary Vim commands

  • Open or create a vim file: vim [filename and extension]

    vim phpinfo.php # create or open a php file named phpinfo in the current directory
    
  • Edit a vim file: press the "i" key

    Pressing the "i" key will change the left bottom corner of the screen to display "INSERT," indicating that you are in insert mode and can edit the file.

  • Exit insert mode and return to command mode: press the "ESC" key

    While in insert mode, you can only type text into the file, but to save the changes, you need to return to command mode and enter a specific command.

  • Save a vim file: type ":w" in command mode and press Enter

  • Exit a vim file: type ":q" in command mode and press Enter

Default location of Apache server

/var/www/html

How to test the server

  1. Switch to root account.
  2. Move to the default location of the Apache server.
  3. Create a PHP file in the default location of the Apache server using Vim.
  4. Start the Apache server.
  5. Open a web browser and check if it works correctly.

Step-by-step

sudo su # Enter the password to switch to the root account.
cd /var/www/html # Move to the default location of the Apache server.
ls # Check the files. If you just installed it, there should be only one file named "index.html".
vim phpinfo.php # Create or open a PHP file named "phpinfo".
i # Change to insert mode and type the following contents.
<?php
	phpinfo();
?>
ESC key # Return to command mode in Vim.
:wq # Save and exit Vim.
sudo service apache2 start # Start the Apache server.

Open a web browser and enter http://localhost/phpinfo.php to run it.

"phpinfo();" is a command that retrieves PHP version information and details, so the following output will be displayed.



Logic Gate Truth Tables & Definitions

Logic Gate Truth Tables Java Code !A // NOT A&B // AND ~(A&B) // NAND A|B // OR ~(A|B) // XOR A^B // XOR ~(A^B) // XNOR ~A // Inve...