How to Build a Register and Login System in PHP That Works with Email or a Discord Account

Creating a registration and login system that integrates with Discord will involve a few components:

  1. A MySQL database to store user data.
  2. PHP to handle the registration and login processes.
  3. Discord OAuth2 API integration for Discord-based registration and login.

Let’s outline this step by step:

1. Database Setup

To store and retriever user information, you’re going to need a database. This article assumes you’re using MySQL, which is a common pairing with PHP.

First, create a database and a table for users. Enter these commands into MySQL:

				
					CREATE DATABASE user_auth;

USE user_auth;

CREATE TABLE users (
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    email VARCHAR(255) UNIQUE,
    password VARCHAR(255),
    discord_id BIGINT UNIQUE,
    date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

				
			

2. Register & Login with Email

Create a new PHP file which will handle registration, register.php

				
					<?php
$host = 'localhost';
$db   = 'user_auth';
$user = 'db_username';
$pass = 'db_password';

$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = $_POST['email'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $stmt = $pdo->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
    $stmt->execute([$email, $password]);
}

?>

<form action="register.php" method="post">
    Email: <input type="email" name="email">
    Password: <input type="password" name="password">
    <input type="submit" value="Register">
</form>

				
			

You will also need a Login page, so create another PHP file, login.php

				
					<?php
// Same DB connection as before

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = $_POST['email'];
    $password = $_POST['password'];

    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password'])) {
        // Successfully logged in. You can start a session or set cookies.
        // This is a basic example; you should add more security.
        session_start();
        $_SESSION['user_id'] = $user['id'];
        header('Location: dashboard.php');  // Redirect to a user dashboard.
    } else {
        echo "Invalid login credentials!";
    }
}

?>

<form action="login.php" method="post">
    Email: <input type="email" name="email">
    Password: <input type="password" name="password">
    <input type="submit" value="Login">
</form>

				
			

3. Register and Login with Discord

Firstly, you’d need to create a Discord application and get your Client ID and Client Secret from the Discord Developer Portal.

Discord Redirect

You’ll need to redirect users to Discord’s OAuth2 URL to let them authorize your application.

				
					$clientId = "YOUR_DISCORD_CLIENT_ID";
$redirectUri = "https://yourdomain.com/discord_callback.php";

$discordUrl = "https://discord.com/api/oauth2/authorize?client_id={$clientId}&redirect_uri={$redirectUri}&response_type=code&scope=identify";

echo "<a href='{$discordUrl}'>Login with Discord</a>";

				
			

Discord Callback (discord_callback.php)

After the user authorizes your application, Discord will redirect them back to the provided redirect_uri with an authorization code. You can exchange this code for an access token and get user information.

				
					$clientId = "YOUR_DISCORD_CLIENT_ID";
$clientSecret = "YOUR_DISCORD_CLIENT_SECRET";
$redirectUri = "https://yourdomain.com/discord_callback.php";

if (isset($_GET['code'])) {
    $code = $_GET['code'];
    
    $tokenUrl = "https://discord.com/api/oauth2/token";
    $tokenData = [
        'client_id' => $clientId,
        'client_secret' => $clientSecret,
        'grant_type' => 'authorization_code',
        'code' => $code,
        'redirect_uri' => $redirectUri,
        'scope' => 'identify'
    ];
    
    $tokenOptions = [
        'http' => [
            'header' => "Content-Type: application/x-www-form-urlencoded",
            'method' => 'POST',
            'content' => http_build_query($tokenData)
        ]
    ];

    $context = stream_context_create($tokenOptions);
    $response = file_get_contents($tokenUrl, false, $context);
    $tokenInfo = json_decode($response);

    $access_token = $tokenInfo->access_token;

    // Now use the access token to get user info.
    $userInfo = file_get_contents("https://discord.com/api/users/@me", false, stream_context_create([
        'http' => [
            'header' => "Authorization: Bearer {$access_token}"
        ]
    ]));

    $discordUser = json_decode($userInfo);

    // Check if the user exists in your DB or create a new one with the Discord ID.
    // This is just a basic example and needs further refinement and error handling.
}


				
			

This is a basic structure to get you started. We hope that you found this article helpful and informative!

There are many optimizations and security practices (like CSRF tokens, etc.) that should be applied before using this in a production environment.

Remember to keep your Discord Client Secret safe and never expose it to the client side.