Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

PHP-Auth

> 安全
Open source

Authentication for PHP. Simple, lightweight and secure.

1.2K stars0 likes2 views
WebsiteGitHub

About

Authentication for PHP. Simple, lightweight and secure.

Auth

Authentication for PHP. Simple, lightweight and secure.

Written once, to be used everywhere.

Completely framework-agnostic and database-agnostic.

Why do I need this?

  • There are tons of websites with weak authentication systems. Don’t build such a site.
  • Re-implementing a new authentication system for every PHP project is not a good idea.
  • Building your own authentication classes piece by piece, and copying it to every project, is not recommended, either.
  • A secure authentication system with an easy-to-use API should be thoroughly designed and planned.
  • Peer-review for your critical infrastructure is a must.

Requirements

  • PHP 5.6.0+
    • PDO (PHP Data Objects) extension (pdo)
      • MySQL Native Driver (mysqlnd) or PostgreSQL driver (pgsql) or SQLite driver (sqlite)
    • OpenSSL extension (openssl)
  • MySQL 5.5.3+ or MariaDB 5.5.23+ or PostgreSQL 9.5.10+ or SQLite 3.14.1+ or other SQL databases

Installation

  1. Include the library via Composer [?]:

    $ composer require delight-im/auth
  2. Include the Composer autoloader:

    php
    require __DIR__ . '/vendor/autoload.php';
  3. Set up a database and create the required tables:

    • MariaDB
    • MySQL
    • PostgreSQL
    • SQLite

Upgrading

Migrating from an earlier version of this project? See our upgrade guide for help.

Commercial support

Commercial support, paid features and development services for this library are available upon request: [email protected]

Usage

  • Creating a new instance
  • Registration (sign up)
  • Login (sign in)
  • Email verification
  • Keeping the user logged in
  • Password reset (“forgot password”)
    • Initiating the request
    • Verifying an attempt
    • Updating the password
  • Changing the current user’s password
  • Changing the current user’s email address
  • Changing the current user’s username
  • Re-sending confirmation requests
  • Logout
  • Accessing user information
    • Login state
    • User ID
    • Email address
    • Display name
    • Status information
    • Checking whether the user was “remembered”
    • IP address
    • Additional user information
  • Reconfirming the user’s password
  • Roles (or groups)
    • Checking roles
    • Available roles
    • Permissions (or access rights, privileges or capabilities)
    • Custom role names
  • Two-factor authentication (2FA)
  • Enabling or disabling password resets
  • Throttling or rate limiting
  • Administration (managing users)
    • Creating new users
    • Deleting users
    • Assigning roles to users
    • Taking roles away from users
    • Checking roles
    • Impersonating users (logging in as user)
    • Changing a user’s password
  • Cookies
    • Renaming the library’s cookies
    • Defining the domain scope for cookies
    • Restricting the path where cookies are available
    • Controlling client-side script access to cookies
    • Configuring transport security for cookies
  • Utilities
    • Creating a random string
    • Creating a UUID v4 as per RFC 4122
  • Reading and writing session data

Creating a new instance

…

If you have an open PDO connection already, just re-use it. The database user (e.g. my-username) needs at least the privileges SELECT, INSERT, UPDATE and DELETE for the tables used by this library (or their parent database).

If your web server is behind a proxy server and $_SERVER['REMOTE_ADDR'] only contains the proxy’s IP address, you must pass the user’s real IP address to the constructor in the second argument, which is named $ipAddress. The default is the usual remote IP address received by PHP.

Should your database tables for this library need a common prefix, e.g. my_users instead of users (and likewise for the other tables), pass the prefix (e.g. my_) as the third parameter to the constructor, which is named $dbTablePrefix. This is optional and the prefix is empty by default.

During development, you may want to disable the request limiting or throttling performed by this library. To do so, pass false to the constructor as the fourth argument, which is named $throttling. The feature is enabled by default.

During the lifetime of a session, some user data may be changed remotely, either by a client in another session or by an administrator. That means this information must be regularly resynchronized with its authoritative source in the database, which this library does automatically. By default, this happens every five minutes. If you want to change this interval, pass a custom interval in seconds to the constructor as the fifth argument, which is named $sessionResyncInterval.

If all your database tables need a common database name, schema name, or other qualifier that must be specified explicitly, you can optionally pass that qualifier to the constructor as the sixth parameter, which is named $dbSchema.

If you want to use a PdoDatabase instance (e.g. $db) independently as well, please refer to the documentation of the database library.

Registration (sign up)

…

Note: The anonymous callback function is a closure. Thus, besides its own parameters, only superglobals like $_GET, $_POST, $_COOKIE and $_SERVER are available inside. For any other variable from the parent scope, you need to explicitly make a copy available inside by adding a use clause after the parameter list.

The username in the third parameter is optional. You can pass null there if you don’t want to manage usernames.

If you want to enforce unique usernames, on the other hand, simply call registerWithUniqueUsername instead of register, and be prepared to catch the DuplicateUsernameException.

Note: When accepting and managing usernames, you may want to exclude non-printing control characters and certain printable special characters, as in the character class [\x00-\x1f\x7f\/:@\\]. In order to do so, you could wrap the call to Auth#register or Auth#registerWithUniqueUsername inside a conditional branch, for example by only accepting usernames when the following condition is satisfied:

php
if (\preg_match('/[\x00-\x1f\x7f\/:@\\\\]/', $_POST['username']) === 0) {
    // ...
}

For email verification, you should build an URL with the selector and token and send it to the user, e.g.:

php
$url = 'https://www.example.com/verify_email?selector=' . \\urlencode($selector) . '&token=' . \\urlencode($token);

If you don’t want to perform email verification, just omit the last parameter to Auth#register, i.e. the anonymous function or closure. The new user will be active immediately, then.

Need to store additional user information? Read on here.

Note: When sending an email to the user, please note that the (optional) username, at this point, has not yet been confirmed as acceptable to the owner of the (new) email address. It could contain offensive or misleading language chosen by someone who is not actually the owner of the address.

Login (sign in)

php
try {
    $auth->login($_POST['email'], $_POST['password']);

    echo 'User is logged in';
}
catch (\Delight\Auth\InvalidEmailException $e) {
    die('Wrong email address');
}
catch (\Delight\Auth\InvalidPasswordException $e) {
    die('Wrong password');
}
catch (\Delight\Auth\EmailNotVerifiedException $e) {
    die('Email not verified');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    die('Too many requests');
}

If you want to sign in with usernames on the other hand, either in addition to the login via email address or as a replacement, that’s possible as well. Simply call the method loginWithUsername instead of method login. Then, instead of catching InvalidEmailException, make sure to catch both UnknownUsernameException and AmbiguousUsernameException. You may also want to read the notes about the uniqueness of usernames in the section that explains how to sign up new users.

Email verification

Extract the selector and token from the URL that the user clicked on in the verification email.

php
try {
    $auth->confirmEmail($_GET['selector'], $_GET['token']);

    echo 'Email address has been verified';
}
catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
    die('Invalid token');
}
catch (\Delight\Auth\TokenExpiredException $e) {
    die('Token expired');
}
catch (\Delight\Auth\UserAlreadyExistsException $e) {
    die('Email address already exists');
}
catch (\Delight\Auth\TooManyRequestsException $e) {
    die('Too many requests');
}

If you want the user to be automatically signed in after successful confirmation, just call confirmEmailAndSignIn instead of confirmEmail. That alternative method also supports persistent logins via its optional third parameter.

On success, the two methods confirmEmail and confirmEmailAndSignIn both return an array with the user’s new email address, which has just been verified, at index one. If the confirmation was for an address change instead of a simple address verification, the user’s old email address will be included in the array at index zero.

Keeping the user logged in

The third parameter to the Auth#login and Auth#confirmEmailAndSignIn methods controls whether the login is persistent with a long-lived cookie. With such a persistent login, users may stay authenticated for a long time, even when the browser session has already been closed and the session cookies have expired. Typically, you’ll want to keep the user logged in for weeks or months with this feature, which is known as “remember me” or “keep me logged in”. Many users will find this more convenient, but it may be less secure if they leave their devices unattended.

php
if ($_POST['remember'] == 1) {
    // keep logged in for one year
    $re

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPauthauthenticationauthorizationlogin

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category安全
PricingOpen source

> Related tools

O
OWASP ZAP
开源 Web 应用安全扫描器
O
owasp-wstg-tracker
Simple web app to track OWASP WSTG security testing progress
H
homebridge-mi-gateway-security
XiaoMi Gateway Security plugin for HomeBridge.