Authentication for PHP. Simple, lightweight and secure.
Authentication for PHP. Simple, lightweight and secure.
Authentication for PHP. Simple, lightweight and secure.
Written once, to be used everywhere.
Completely framework-agnostic and database-agnostic.
pdo)mysqlnd) or PostgreSQL driver (pgsql) or SQLite driver (sqlite)openssl)Include the library via Composer [?]:
$ composer require delight-im/authInclude the Composer autoloader:
require __DIR__ . '/vendor/autoload.php';Set up a database and create the required tables:
Migrating from an earlier version of this project? See our upgrade guide for help.
Commercial support, paid features and development services for this library are available upon request: [email protected]
…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.
…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:
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.:
$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.
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.
Extract the selector and token from the URL that the user clicked on in the verification email.
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.
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.
if ($_POST['remember'] == 1) {
// keep logged in for one year
$reNo open issues yet, or sync has not completed.