How to Create a Magic Link Login System in Core PHP

The traditional password-based authentication system is showing its age. Users are fatigued by remembering complex passwords, and developers are constantly battling data breaches and credential stuffing. Enter the Passwordless Login—specifically, the "Magic Link" system.

By utilizing magic links, you remove the password entirely. Users enter their email, receive a secure link, and click it to log in. It’s a seamless, secure, and user-friendly experience popularized by platforms like Slack and Medium.

In this guide, we will build a robust, secure, and straightforward magic link authentication system using vanilla PHP and MySQL.

Prerequisites

Before diving into the code, ensure you have the following environment set up:

  • A server running PHP 7.4+ or PHP 8.x.

  • A MySQL/MariaDB database.

  • A working local or production mail server (or an SMTP tool like PHPMailer) to send emails.

Step 1: Designing the Database

We need a database architecture to store our users and their temporary login tokens. A secure implementation separates the user data from the ephemeral tokens.

Execute the following SQL to create your tables:

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

CREATE TABLE login_tokens (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    token_hash VARCHAR(64) NOT NULL,
    expires_at DATETIME NOT NULL,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

Note: We store a token_hash rather than the plain text token. If your database is ever compromised, the attacker cannot use the stolen tokens to log in, as they must be used before expiration and require the original unhashed string.

Step 2: The Login Interface (HTML)

The frontend is incredibly minimal. We only need an input field for the user's email address. Create an index.php file:

<head>
    <meta charset="UTF-8">
    <title>Magic Link Login</title>
    <style>
        body { font-family: system-ui, sans-serif; display: flex; justify-content: center; padding-top: 50px; }
        .login-box { border: 1px solid #ccc; padding: 30px; border-radius: 8px; max-width: 400px; width: 100%; }
        input[type="email"], button { width: 100%; padding: 10px; margin-top: 10px; box-sizing: border-box; }
        button { background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
    </style>
</head>
<body>
    <div class="login-box">
        <h2>Sign In</h2>
        <p>Enter your email to receive a magic login link.</p>
        <form action="request_link.php" method="POST">
            <input type="email" name="email" placeholder="[email protected]" required>
            <button type="submit">Send Magic Link</button>
        </form>
    </div>
</body>

Step 3: Generating and Sending the Token

When the user submits their email, the backend must verify the user, generate a secure token, store its hash, and email the link. We will use random_bytes() for cryptographic security.

Create request_link.php:

// Database connection (use your own credentials)
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['email'])) {
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

    // 1. Check if user exists (for simplicity, we assume they do, or we create them)
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if (!$user) {
        // Optional: Auto-register user if they don't exist
        $stmt = $pdo->prepare("INSERT INTO users (email) VALUES (?)");
        $stmt->execute([$email]);
        $userId = $pdo->lastInsertId();
    } else {
        $userId = $user['id'];
    }

    // 2. Generate a secure random token
    $token = bin2hex(random_bytes(32)); // 64 characters long
    $tokenHash = hash('sha256', $token);
    
    // Set expiration time (e.g., 15 minutes from now)
    $expiresAt = date('Y-m-d H:i:s', strtotime('+15 minutes'));

    // 3. Store the hashed token in the database
    $stmt = $pdo->prepare("INSERT INTO login_tokens (user_id, token_hash, expires_at) VALUES (?, ?, ?)");
    $stmt->execute([$userId, $tokenHash, $expiresAt]);

    // 4. Construct the Magic Link
    $loginLink = "https://yourwebsite.com/verify.php?token=" . $token . "&email=" . urlencode($email);

    // 5. Send the email (In production, use a library like PHPMailer or a transactional email API)
    $subject = "Your Magic Login Link";
    $message = "Click the link below to log in securely:\n\n" . $loginLink . "\n\nThis link expires in 15 minutes.";
    $headers = "From: [email protected]";

    // Uncomment to send the actual email:
    // mail($email, $subject, $message, $headers);

    echo "A magic link has been sent to your email! Please check your inbox.";
} else {
    header("Location: index.php");
    exit;
}

Step 4: Verifying the Magic Link

When the user clicks the link in their email, they are directed to verify.php. This script checks the token against the database, ensures it hasn't expired, and establishes a user session.

Create verify.php:

session_start();
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if (isset($_GET['token']) && isset($_GET['email'])) {
    $token = $_GET['token'];
    $email = filter_var($_GET['email'], FILTER_SANITIZE_EMAIL);  
    // Hash the incoming token to compare with the database
    $tokenHash = hash('sha256', $token);

  // 1. Fetch user ID based on email
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user) {
        $userId = $user['id'];

        // 2. Look for a valid, non-expired token for this user
        $stmt = $pdo->prepare("SELECT id FROM login_tokens WHERE user_id = ? AND token_hash = ? AND expires_at > NOW()");
        $stmt->execute([$userId, $tokenHash]);
        $validToken = $stmt->fetch();

        if ($validToken) {
            // 3. Token is valid! Log the user in.
            $_SESSION['user_id'] = $userId;
            $_SESSION['logged_in'] = true;

            // 4. BURN THE TOKEN (Single-use policy)
            $stmt = $pdo->prepare("DELETE FROM login_tokens WHERE id = ?");
            $stmt->execute([$validToken['id']]);

            // Redirect to the protected dashboard
            header("Location: dashboard.php");
            exit;
        } else {
            echo "Invalid or expired link. Please request a new one.";
        }
    } else {
        echo "User not found.";
    }
} else {
    echo "Missing token parameters.";
}

Step 5: Production-Level Security Considerations

While the code above works perfectly, moving this into a high-traffic production environment requires a few strict security policies:

  1. Single-Use Tokens (Implemented): Notice the DELETE statement in step 4. A magic link must never be reusable. Once clicked, it should instantly invalidate.

  2. Rate Limiting: Prevent malicious bots from spamming your email API. Implement rate limiting on request_link.php (e.g., max 3 requests per IP address every 10 minutes).

  3. Short Expiration Windows: Keep the expires_at window tight. 10 to 15 minutes is the industry standard.

  4. Database Cleanup: Over time, unclicked tokens will pile up. Implement a cron job or scheduled task to delete tokens where expires_at < NOW().

  5. Session Fixation Protection: After verifying the user and before setting $_SESSION, always call session_regenerate_id(true) to prevent session fixation attacks.

Conclusion

Implementing a passwordless login system in PHP drastically simplifies the user journey while simultaneously stripping away the liability of storing user passwords. By utilizing secure token generation, hashing algorithms, and enforcing strict single-use policies, you can provide a modern, frictionless authentication flow for your web applications.