이 블로그 검색

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.



Web Hacking: Cookie Tampering, Directory Traversal, Session Hijacking, Authentication Bypass, Brute Force Attack

Web hacking is a common technique used by attackers to exploit vulnerabilities in web applications. In this article, we will explore some common types of web attacks, including cookie tampering, directory traversal, session hijacking, authentication bypass, and brute force attacks.

Cookie Tampering

Definition

Cookie tampering refers to the malicious act of modifying cookie values used in web applications.

Purpose

Cookies are stored on the client-side and are used to maintain the state between the client and server (such as authentication, session management, user identification, etc.).

Prevention

  • Authentication and encryption for cookies
  • Filtering and validation for input values
  • Filtering for output values
  • Appropriate cookie settings based on the purpose and duration of use

Example

Using Burp Suite:

Let's confirm a successful login. The response status code is 302.

A status code in the 300s indicates redirection. This means that the user has been redirected to another webpage.

Let's check the cookies. We can see that the username is stored in the cookie, rather than using a session to differentiate users.

By changing the value of loginUser to "admin," we can steal authorization through cookie tampering.

Directory Traversal

Another name

  • File Path Traversal

Definition

Directory traversal is an attack that involves guessing the paths of files or directories within a website in order to directly access those files or directories.

Prevention

To prevent these vulnerabilities, it is important to:

  • Limit access to files or directories
  • Filter and validate input values
  • Filter output values

Example

Using Burp Suite:

If the homepage is split into step1 and step2, you can try to access step3 directly without logging in.

Session Hijacking

Another name

  • Session Fixation

Definition

Session hijacking involves an attacker acquiring a valid session and then using that session to impersonate the user or access other accounts.

Prevention

Proper session management is essential:

  • Generate session IDs using random and unpredictable values
  • Set a reasonable session expiration time
  • Use encrypted protocols such as SSL or TLS to transmit session IDs

Example

  1. The attacker monitors network traffic to capture the user's session ID.
  2. The attacker uses the stolen session ID to log in to the website as an authenticated user.
  3. The attacker can now perform malicious actions with the user's privileges.

Authentication Bypass

Another name

  • Login Bypass

Definition

Authentication bypass occurs when login is possible without verifying the ID and password or when login can be done through other means.

Prevention

  • Authenticate and verify login credentials

Example

  1. The attacker discovers a vulnerable authentication mechanism (e.g., weak password policy, missing input validation).
  2. The attacker finds a way to bypass the authentication mechanism (e.g., SQL injection, using default passwords, tampering with authentication tokens).
  3. The attacker bypasses the authentication process and gains unauthorized access to the system.
  4. The attacker can now steal information or manipulate the system without being authenticated.

Brute Force Attack

Definition

A brute force attack is an attack that guesses passwords by trying all possible combinations.

Prevention

  • Encourage users to use safe passwords
  • Use blacklisting to lock accounts after a certain number of failed logins
  • Add security features such as CAPTCHA

Example

Using Burp Suite:

Although the Intruder function in Burp Suite can be used, it is much faster to use Python:

import httplib2

# Suppose that the GET request is made to example.php?otpNum=0000.
# URL of target website (in this case, example.php)
url = "<http://example.php>"

# httplib2 instance creation
http_obj = httplib2.Http()

# Range of otp_num (0000 to 9999)
for otp_num in range(10000):
    # Format otp_num into a 4-digit number (e.g., 0035)
    otp_num_formatted = f"{otp_num:04d}"

    # Add otp_num parameter to GET request
    request_url = f"{url}?otpNum={otp_num_formatted}"
    response, content = http_obj.request(request_url, method="GET")

    # Depending on how the results are found, the processing can be modified.
    # For example, if the server returns a specific message, it can be checked.
    # Use print(content) to check and set success conditions.
    if not b"Login Fail" in content:
        print(f"Success! OTP number is: {otp_num_formatted}")
        break
    else:
        print(f"Failed for OTP number: {otp_num_formatted}")


Understanding the Key Features of Burp Suite

Burp Suite

Definition

Burp Suite is a web proxy program (packet manipulation program) that sits between the client and the server.

It allows interception of data being sent between the two and provides various tools such as vulnerability scanners and interface analysis tools for web applications.

Usage

  • Detecting vulnerabilities in web applications

  • Fixing security flaws

  • Analyzing web application interfaces

Installation on Ubuntu

  1. Install Java

    sudo apt-get install openjdk-8-jre
    
  2. Download Burp Suite Community edition

    https://portswigger.net/burp/communitydownload

  3. Run the installation file

    Open the terminal in the download folder

    sudo bash burpsuite_community_linux_v2021_9_1.sh
    
  4. Run Burp Suite

    Go to /usr/local/bin, the default installation location, and run Burp Suite from the terminal

    /BurpSuiteCommunity
    

Key Features of Burp Suite

Intercept

Definition

One of the features of Burp Suite allows you to stop requests being sent to the server. You can modify the packet in the middle and send it.

Steps

  1. Turn on proxy-intercept-intercept

  2. Open the browser

All requests made by the opened Chromium browser will be stopped in the middle, and cannot be sent without permission from Burp Suite.

  • Forward: Sends the stopped request to the server. You can modify the request before sending it.

  • Drop: Deletes the stopped request. The server does not receive this request.

History

Definition

One of the features of Burp Suite allows you to see all requests and responses made in the Chromium browser.

Steps

  1. proxy-intercept-HTTP history

  2. Open the browser

You can view all requests and responses made in the opened Chromium browser.

Repeater

Definition

One of the features of Burp Suite allows you to send a request multiple times with modifications to the server and see the response immediately after sending.

Steps

  1. proxy-intercept-HTTP history-Select the request you want to repeat-Right-click-Send to Repeater

  2. Modify the request and click "Send" to see the response

Intruder

Definition

One of the features of Burp Suite allows you to brute force passwords by sending repeated requests.

Steps

  1. proxy-intercept-HTTP history-Select the request you want to repeat-Right-click-Send to Intruder

  2. position-clear-select the part you want to modify repeatedly-Add

  3. payload-Set how to modify the selected part

  4. Start attack

The attack speed is a bit slow and you have to search from predefined places, so if you need complex conditions, it is better to write and attack separately with Python.

If you use Python libraries such as httplib2 or requests, you can replace the Intruder function.

Python Example

HTTP request: GET example.php?otp_num=1111 HTTP/1.1

Variable: otp_num

Range of attempts: 0000~9999

Condition: Success

import httplib2

# Target website URL (here: example.com)
url = "<https://example.com/example.php>"

# Create an httplib2 instance
http_obj = httplib2.Http()

# Range of otp_num (0000 to 9999)
for otp_num in range(10000):
    # Format otp_num as a 4-digit number (e.g., 0035)
otp_num_formatted = f"{otp_num:04d}"

# Add otp_num parameter to GET request
request_url = f"{url}?otp_num={otp_num_formatted}"
response, content = http_obj.request(request_url, method="GET")

# You can modify the processing depending on how you want to find the desired result.
# For example, if the server returns a specific message, you can check it.
if b"Success" in content:
    print(f"Success! OTP number is: {otp_num_formatted}")
    break
else:
    print(f"Failed for OTP number: {otp_num_formatted}")
import requests

# Target website URL (here: example.com)
url = "<https://example.com/example.php>"

# Range of otp_num (0000 to 9999)
for otp_num in range(10000):
    # Format otp_num as a 4-digit number (e.g., 0035)
    otp_num_formatted = f"{otp_num:04d}"

    # Add otp_num parameter to GET request
    response = requests.get(url, params={"otp_num": otp_num_formatted})

    # You can modify the processing depending on how you want to find the desired result.
    # For example, if the server returns a specific message, you can check it.
    if "Success" in response.text:
        print(f"Success! OTP number is: {otp_num_formatted}")
        break
    else:
        print(f"Failed for OTP number: {otp_num_formatted}")

2023년 4월 9일 일요일

The Evolution of Authorization: A Brief History Leading up to OAuth 2.0

The Importance of HTTP and Login Authentication Technology

When the Internet was first created, the HTTP protocol was a kind of rule to quickly exchange information. Servers simply prepared data and responded to requests without storing client information, which was known as the stateless characteristic.

However, as technology progressed, servers needed to identify who the client was. For example, shopping websites needed to display different items in each client's shopping cart. This led to the creation of various login authentication technologies.

Cookie

The first login authentication technology, cookies, stored the user ID and password on the server. When the client sent the ID and password to the server, the server checked them.

Cookies are typically stored in the HTTP URI's header, which is easy to access during information requests. Therefore, attackers often intercepted the information in the middle of the request and obtained the user ID and password.

Session

Session created a storage area to store the client's user ID and password and generated a unique Session ID to save it. When the client logged in, the client sent the Session ID instead of the user ID and password to the server, which used it to identify the client.

Since the user ID and password were only sent once, it was difficult to intercept them. Also, the Session ID was not related to the user ID and password, which made it more secure than cookies. However, it was still possible to log in using the Session ID, so security was still not enough.

To improve security, the Session ID was given an expiration time. However, it was inconvenient for clients and not very effective.

Access Token

Next, the Access Token was created. Like the Session ID, it is used for authentication, but the Access Token collects and encrypts the necessary information for authentication. This information is usually stored using the JSON Web Token (JWT) method.

JWT (JSON Web Token) Components

[Header].[Payload].[Signature]
  • Header: Contains the type and encryption method of the Access Token.

    {
      "typ": "JWT",
      "alg": "SHA256"
    }
    
  • Payload: Contains the necessary information for authentication, such as the token creation time, activation date, expiration date, etc. It does not contain client-related information (such as ID and password).

    {
      "sub": "1",
      "iss": "ori",
      "exp": 1636989718,
      "iat": 1636987918
    }
    
  • Signature: A string created using the SHA256 algorithm specified in the header, using the information in the payload and the server's private key. This is used to authenticate the token, so if the token is tampered with, it can be detected immediately.

    {
      "SHA": "9F69FA131C4CA518D3CCE296013D9A3C2B4AA63CA02583C8B6F1F7F354A1D874"
    }
    

Access Token and Refresh Token

One problem with Access Tokens is that they cannot create a new token before the expiration of the current token because the encryption uses an expiration date. However, if the expiration date is set to a short period of time, it is inconvenient for clients. This led to the creation of the Refresh Token.

Access Tokens are issued with a short expiration date, while Refresh Tokens are issued with a long expiration date. When the Access Token expires, the client uses the Refresh Token to authenticate and obtain a new Access Token.

Since the Refresh Token is only sent to the server when the Access Token expires, it is difficult to intercept. Also, since Access Tokens are frequently reissued, it becomes more difficult to intercept them.

OAuth (Open Authorization) 1.0

OAuth 1.0 added another application to protect IDs and passwords. This application was used as an independent service for user authentication and was called the consumer.

User: User

Service provider: Google OAuth Service

Consumer: Twitter

  1. The user attempts to log in to Twitter.
  2. Twitter requests a Request Token from Google OAuth Service.
  3. Google OAuth Service checks the Key and Secret sent by Twitter and generates a Request Token.
  4. Twitter shows the login page through Google OAuth Service (redirect).
  5. The user's login information (ID and password) is sent to Google OAuth Service.
  6. Google OAuth Service checks the Request Token and the ID and password (login authentication).
  7. Google OAuth Service informs Twitter that the authentication was successful.
  8. Twitter requests an Access Token from Google OAuth Service since the user has been authenticated.
  9. Google OAuth Service generates and sends an Access Token to Twitter.
  10. Twitter gives the user the Access Token. Connection complete.
  11. The user logs in using the Access Token until it expires.

In summary, OAuth 1.0 is a way for the user (User), the site the user wants to use (Consumer), and another web service that holds user information (Service Provider) to interact with each other to function. However, this method is complicated to implement, and the lack of Refresh Token means that a new token cannot be created before the expiration of the existing Access Token. Additionally, authentication was only possible through web pages.

OAuth (Open Authorization) 2.0

Disadvantages of OAuth 1.0 Improvements in OAuth 2.0
Lack of security during communication Use of HTTPS instead of HTTP
Too complex Simplification of functionality
Inability to issue new tokens before the expiration of access tokens Introduction of Refresh Tokens
Login authentication only possible through web pages Expansion of login authentication methods

In addition, the separation of the server responsible for login authentication and the server that processes user requests made it difficult for Access Tokens, user IDs, and passwords to be compromised.

Resource Server A server that manages resources and responds to requests with an Access Token
Authorization Server A server that authenticates clients and issues tokens for clients to access services on the resource server
Resource Owner A user who owns an account on the resource server
Client A website that uses the resource server's API to retrieve data
Access Token A token that allows requests for resources to the resource server
Refresh Token A token that allows the client to request a new Access Token from the authorization server

Authorization Code Grant

  • Recommended usage
  • High level of security: Access Token is not directly transmitted to the client, preventing potential leaks
  • Generally used on the backend server

  1. The user sends their ID and password to the authorization server via the client. If the login is successful, the authorization server issues an authorization code to the user.
  2. The client sends the authorization code to the authorization server and requests an Access Token. The authorization server verifies the authorization code and issues an Access Token and a Refresh Token.
  3. The client can access the resources on the resource server using the issued Access Token.
  4. When the Access Token expires, the client uses the Refresh Token to request a new Access Token from the authorization server.

Implicit Grant

  • Recommended to use
  • The most commonly used authentication method
  • Typically used when a user logs into a shopping mall (User Agent Application)

  1. The user attempts to log in to the authentication server using the client. After the authentication server completes the login authentication, it issues an access token.
  2. The authentication server returns a redirection response that includes the access token to the client. The access token is included in the URI fragment.
  3. The client extracts the access token from the redirection response and attempts to access the resource on the resource server using the token. After the resource server verifies the validity of the access token with the authentication server, the client can access the requested resource.

Resource Owner Password Credentials Grant

  • Not recommended to use
  • Can be used in all types of applications
  • Typically used in API connections

  1. The user submits their ID, password, and client information to the authentication server using the client. After the authentication server authenticates the login and client information, it issues an access token.
  2. The client can access the resource server's resource using the issued access token.

Client Credentials Grant

  • Not recommended
  • Access token can be issued directly based on client authentication
  • Used to access application data, not user-related data

  1. The client sends its client information (client ID and client secret) to the authorization server. If the client information is authenticated by the authorization server, an access token is issued.
  2. The client can use the access token to access resources on the resource server.

Device Code Grant

  • Not recommended
  • Authentication is carried out using a separate device
  • Used when there is no web browser or limited input device (e.g., smart TV, game console)

  1. The user starts the client application on the device with limited input. The client requests a device code, a user code, and a verification URL from the authorization server.
  2. The authorization server returns a device code, a user code, and a verification URL to the client. The user goes to the verification URL on a different device (e.g., smartphone, computer) to enter the user code and complete the login.
  3. The client sends the device code and client identifier to the authorization server and requests an access token.
  4. After the user completes the login authentication on the verification URL, the authorization server issues an access token, and the client can use the access token to access resources on the resource server.

Refresh Token Grant

Access tokens are refreshed using a refresh token, and the original access token expires after a certain period of time.

2023년 4월 7일 금요일

HTTP GET vs POST: Which One is Right for Your Web Application?

 

Purpose

In the HTTP protocol, there are two ways to send data: GET and POST.

Let's explore their differences and advantages and disadvantages.

Components of HTTP Request

[Scheme]://[Host]:[Port][Path]?[Query]#[Fragment]

[Header]

Example of HTTP URI Components

http://www.example.com:1030/software?id=test#section-4

Scheme Host Port  Path Query Fragment
http ://http://www.example.com/ :1030  /software ?id=test #section-4

Sending Data with GET

This method sends data by declaring parameters in the query section of the HTTP URI.

Example of GET

http://www.example.com?id=test

Advantages

  • Can be cached in the URI, allowing for bookmarks, backtracking, etc.
  • Faster than POST
  • Parameter values are visible, so contents can be guessed.

Disadvantages

  • Limited length for the URI
  • Parameter values are visible, so contents can be guessed, making it less secure.

PHP Code to Receive Data Sent with GET

<?php
$data = $_GET['a'];
echo "$data";
?>

Sending Data with POST

This method sends data by declaring parameters in the header section of the HTTP request.

Example of POST

$name=Han is the parameter and data being sent.

POST /login HTTP/1.1
Host: www.example.com
Content-Length: 255
Cache-Control: max-age=242342
Upgrade-Insecure-Requests: 134423423
Origin: <http://www.example.com>
Content-Type: application/x-www-form-urlencoded

$name=Han

Advantages

  • No length limit
  • Parameter values are not visible, so it is more secure.

Disadvantages

  • Cannot be cached, making it impossible to bookmark or backtrack.

PHP Code to Receive Data Sent with POST

<?php
$data = $_POST['a'];
echo "$data";
?>

MySQL on APM: Basic Usage and Configuration

 Starting MySQL Server

service mysql start

Creating a Database as a MySQL User

Username: root

Database name: test

mysqladmin -u root create test -p

It will ask for a password, but as there is no default password, simply press Enter.

Setting a Password for the Root Account

Account name: root

Password: 1234

use mysql
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '1234'

Connecting to the MySQL Server as a User

Username: root

If successful, the prompt will change to mysql>:

mysql -u root -p

Listing Available Databases

show databases;

Selecting a Database to Use

use test;

Creating a Table

Table name: users

create table users (
        id varchar(10) primary key,
        name varchar(20) not null,
        password varchar(10) not null
        );

Listing Available Tables

show tables;

Describing a Table

Check the data type and constraints for each column.

DESC tables;

Retrieving Table Data

Table name: users

select * from users;

Inserting Data into a Table

Table name: users

insert into users (id,name,password) values (0, "name0", "pass0");

Importing a Database

Installing Git

apt-get install git

Cloning a Git Repository

Example database: https://github.com/datacharmer/test_db

git clone <https://github.com/datacharmer/test_db.git>
cd test_db

Importing SQL Files

mysql < employees.sql

Changing the MySQL Port

The default MySQL port is 3306. To change it, modify the port section in the mysqld.cnf file.

vim /etc/mysql/mysql.conf.d/mysqld.cnf

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