FusionAuth QuickStart for PHP
On this page
This QuickStart explains how to add a login page and authentication to a website built with PHP. You'll begin with a simple PHP app that allows visitors to edit a file. Then, you'll add authentication to the app with a FusionAuth instance. Finally, you'll extend the app to handle multiple independent users with user data provided by FusionAuth.
This tutorial should take between 5 and 15 minutes; less if you already have prerequisites like Docker installed.
Prerequisites#
This QuickStart requires:
If you use macOS or Windows, you need one of the following container management tools:
- Docker Desktop
- OrbStack (to use OrbStack for
docker composecommands after installation, rundocker context use orbstack) - Podman (in the commands below, replace
dockerwithpodman)
Create a Simple PHP App#
For this QuickStart, we'll use a single-file PHP app that reads and writes data to a text file:
-
Create a folder for the app and navigate into it:
$ mkdir php-quickstart && cd php-quickstart -
Create a file named
index.phpwith the following code:<?php $noteFile = __DIR__ . '/note.txt'; if ($_SERVER['REQUEST_METHOD'] === 'POST') { file_put_contents($noteFile, $_POST['content'] ?? ''); header('Location: /', true, 303); exit; } $note = is_file($noteFile) ? file_get_contents($noteFile) : ''; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Notes</title> </head> <body> <h1>Notes</h1> <form method="post" action="/"> <label for="content">Your note</label><br> <textarea id="content" name="content" rows="8" cols="40"><?= htmlspecialchars($note) ?></textarea><br> <button type="submit">Save Changes</button> </form> </body> </html>When the form is submitted, the app saves the note to
note.txtand redirects back to the page. Otherwise, it displays the note in a form. -
Run the app with PHP's built-in web server:
$ php -S localhost:3000 index.phpPassing
index.phpas the router script sends every request through it, so the server doesn't servenote.txtor other files in the folder directly. -
Open the app at http://localhost:3000.
-
Type "Hello PHP" in the text area, then click Save Changes .
-
In a file browser or terminal, look in the
php-quickstartfolder. You should see a new file namednote.txt, with text content "Hello PHP". -
Press Ctrl+C on your keyboard to stop the server.
Install and Run FusionAuth#
Before we can add authentication to our PHP app, we need a local FusionAuth instance:
-
Open your container management tool (listed in the prerequisites above).
-
From the
php-quickstartfolder, clone the GitHub repository for the FusionAuth instance you'll use with this QuickStart:$ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git -
Navigate into the cloned directory:
$ cd fusionauth-quickstart-app -
To start a local instance of FusionAuth, run the following command (omit the
-dflag to see all Docker logs):$ docker compose up -d -
Wait until all networks, volumes, and containers show a green status of Healthy, Started, or Created. This may take a few minutes, depending on your network speed and cached dependencies.
-
Open http://localhost:9011/admin to access the FusionAuth Admin UI.
-
Log in with these credentials:
- Login:
admin@example.com - Password:
password
- Login:
-
Navigate to Applications . In the QuickStart App row, click Select -> Edit , then click the OAuth tab. On this page, you can find your client Id and client secret, and set redirect and logout URLs. In the next part of this QuickStart, we'll use these values to connect our PHP app with FusionAuth.
-
Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our PHP app, and because FusionAuth supports SSO, we need to log out of our admin account before we can log in as a normal user.
Add FusionAuth to the PHP App#
Now that you have a working instance of FusionAuth and a working PHP app, let's use FusionAuth to add login to your PHP app:
-
Navigate out of the
fusionauth-quickstart-appfolder, back to thephp-quickstartfolder that containsindex.phpandnote.txt:$ cd .. -
Install the League OAuth 2.0 Client, which handles communication with our FusionAuth instance:
$ composer require league/oauth2-client:2.10.0Composer creates a
composer.jsonfile and installs the library in thevendorfolder. -
Create a file named
config.phpwith the following contents (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI):<?php return [ 'fusionAuthUrl' => 'http://localhost:9011', 'clientId' => 'f0510a74-da7a-4101-a474-05e7f1d5ba7e', 'clientSecret' => 'super-secret-secret-that-should-be-regenerated-for-production', 'redirectUri' => 'http://localhost:3000/oauth-callback', ]; -
Replace the contents of
index.phpwith the following code:<?php require __DIR__ . '/vendor/autoload.php'; use League\OAuth2\Client\Provider\GenericProvider; $config = require __DIR__ . '/config.php'; $provider = new GenericProvider([ 'clientId' => $config['clientId'], 'clientSecret' => $config['clientSecret'], 'redirectUri' => $config['redirectUri'], 'urlAuthorize' => $config['fusionAuthUrl'] . '/oauth2/authorize', 'urlAccessToken' => $config['fusionAuthUrl'] . '/oauth2/token', 'urlResourceOwnerDetails' => $config['fusionAuthUrl'] . '/oauth2/userinfo', 'scopes' => ['openid'], 'pkceMethod' => GenericProvider::PKCE_METHOD_S256, ]); function redirect(string $url): never { header('Location: ' . $url, true, 303); exit; } session_start(); $_SESSION['csrf_token'] ??= bin2hex(random_bytes(32)); $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $isPost = $_SERVER['REQUEST_METHOD'] === 'POST'; if ($isPost && !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) { http_response_code(400); exit('Invalid CSRF token'); } if ($path === '/login/start') { $authorizationUrl = $provider->getAuthorizationUrl(); $_SESSION['oauth_state'] = $provider->getState(); $_SESSION['oauth_pkce_code'] = $provider->getPkceCode(); redirect($authorizationUrl); } if ($path === '/oauth-callback') { if (!isset($_GET['code'], $_GET['state'], $_SESSION['oauth_state']) || $_GET['state'] !== $_SESSION['oauth_state']) { http_response_code(400); exit('Invalid login response'); } $provider->setPkceCode($_SESSION['oauth_pkce_code']); $accessToken = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]); $user = $provider->getResourceOwner($accessToken)->toArray(); session_regenerate_id(true); unset($_SESSION['oauth_state'], $_SESSION['oauth_pkce_code']); $_SESSION['user_id'] = $user['sub']; redirect('/'); } if ($path === '/logout' && $isPost) { session_destroy(); redirect($config['fusionAuthUrl'] . '/oauth2/logout?' . http_build_query(['client_id' => $config['clientId']])); } if ($path === '/login') { ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Log in</title> </head> <body> <h1>Log in to Notes</h1> <a href="/login/start">Log in with FusionAuth</a> </body> </html> <?php exit; } if (!isset($_SESSION['user_id'])) { redirect('/login'); } $noteFile = __DIR__ . '/note.txt'; if ($isPost) { file_put_contents($noteFile, $_POST['content'] ?? ''); redirect('/'); } $note = is_file($noteFile) ? file_get_contents($noteFile) : ''; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Notes</title> </head> <body> <h1>Notes</h1> <form method="post" action="/"> <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>"> <label for="content">Your note</label><br> <textarea id="content" name="content" rows="8" cols="40"><?= htmlspecialchars($note) ?></textarea><br> <button type="submit">Save Changes</button> </form> <form method="post" action="/logout"> <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>"> <button type="submit">Logout</button> </form> </body> </html>The new code connects the app to FusionAuth:
GenericProvidertells the League OAuth 2.0 Client how to talk to FusionAuth. It uses the client Id, client secret, the FusionAuth authorize, token, and UserInfo endpoints, and PKCEAn extension to OAuth 2.0 that mitigates authorization code interception attacks using dynamic code verifiers and challenges..session_startstarts a native PHP session, which keeps the user logged in to the app with a cookie. The session also stores a random CSRF token. Both forms include the token in a hidden field, and the app rejects anyPOSTrequest without a matching token, to prevent CSRFAn attack in which a malicious site makes the user's browser send an unwanted request to a site where the user is logged in. The OAuth 2.0stateparameter protects the authorization flow from CSRF..- The
/loginroute shows a page with a Log in with FusionAuth link to/login/start, which sends the user to the FusionAuth login page. Before it redirects, the app stores thestatevalue and PKCE code verifier in the session. - The
/oauth-callbackroute receives the authorization code from FusionAuth. It checks thatstatematches the session, exchanges the code and code verifier for an access token, and uses the access token to request the user's details from FusionAuth's UserInfo endpoint. The app then stores the user's Id (thesubclaim) in the session. - The
/logoutroute destroys the PHP session, then sends the user to FusionAuth's/oauth2/logoutendpoint so the FusionAuth session ends too. FusionAuth then sends the user to the app's login page. - Any other request without a logged-in user redirects to
/login.
-
Run the app, which now uses FusionAuth login:
$ php -S localhost:3000 index.php -
Open the app at http://localhost:3000 and click Log in with FusionAuth .
-
Log in with the following credentials:
- Login:
richard@example.com - Password:
password
- Login:
-
Edit and save the note in the authenticated PHP app.
-
Click Logout . FusionAuth ends your session and sends you back to the login page.
-
Press Ctrl+C on your keyboard to stop the server.
Add Independent Notes for Each User#
To see a more realistic example of FusionAuth usage, we can improve the app even more, so every user gets a unique note to edit. To accomplish this, we'll use FusionAuth's user data:
-
Open the FusionAuth Admin UI at http://localhost:9011/admin.
-
Log in with the following credentials:
- Login:
admin@example.com - Password:
password
- Login:
-
Navigate to Applications . In the QuickStart App row, click Select -> Edit , then click the Registration tab.
- Under Self-service registration, check that Registration mode is set to Create registration. The QuickStart configuration has already turned on self-service registration.
- In the Registration field list, turn on the Enabled and Required switches for the following rows:
- Birthdate
- First name
- Last name
-
Click Save in the top right of the page to save your changes to self-service registration.
-
Navigate to Users . In the Richard Hendricks row, click Select -> Manage .
-
In the Source tab, look for the
firstNameandlastNamefields. That's what we'll use to personalize the UI for each user. We'll use the user'sidfield to generate a unique name for each user's note. -
Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our PHP app.
-
Replace the contents of
index.phpwith the following code:<?php require __DIR__ . '/vendor/autoload.php'; use League\OAuth2\Client\Provider\GenericProvider; $config = require __DIR__ . '/config.php'; $provider = new GenericProvider([ 'clientId' => $config['clientId'], 'clientSecret' => $config['clientSecret'], 'redirectUri' => $config['redirectUri'], 'urlAuthorize' => $config['fusionAuthUrl'] . '/oauth2/authorize', 'urlAccessToken' => $config['fusionAuthUrl'] . '/oauth2/token', 'urlResourceOwnerDetails' => $config['fusionAuthUrl'] . '/oauth2/userinfo', 'scopes' => ['openid', 'profile'], 'scopeSeparator' => ' ', 'pkceMethod' => GenericProvider::PKCE_METHOD_S256, ]); function redirect(string $url): never { header('Location: ' . $url, true, 303); exit; } session_start(); $_SESSION['csrf_token'] ??= bin2hex(random_bytes(32)); $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $isPost = $_SERVER['REQUEST_METHOD'] === 'POST'; if ($isPost && !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) { http_response_code(400); exit('Invalid CSRF token'); } if ($path === '/login/start') { $authorizationUrl = $provider->getAuthorizationUrl(); $_SESSION['oauth_state'] = $provider->getState(); $_SESSION['oauth_pkce_code'] = $provider->getPkceCode(); redirect($authorizationUrl); } if ($path === '/oauth-callback') { if (!isset($_GET['code'], $_GET['state'], $_SESSION['oauth_state']) || $_GET['state'] !== $_SESSION['oauth_state']) { http_response_code(400); exit('Invalid login response'); } $provider->setPkceCode($_SESSION['oauth_pkce_code']); $accessToken = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]); $user = $provider->getResourceOwner($accessToken)->toArray(); session_regenerate_id(true); unset($_SESSION['oauth_state'], $_SESSION['oauth_pkce_code']); $_SESSION['user_id'] = $user['sub']; $_SESSION['user_name'] = trim(($user['given_name'] ?? '') . ' ' . ($user['family_name'] ?? '')) ?: 'writer'; redirect('/'); } if ($path === '/logout' && $isPost) { session_destroy(); redirect($config['fusionAuthUrl'] . '/oauth2/logout?' . http_build_query(['client_id' => $config['clientId']])); } if ($path === '/login') { ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Log in</title> </head> <body> <h1>Log in to Notes</h1> <a href="/login/start">Log in with FusionAuth</a> </body> </html> <?php exit; } if (!isset($_SESSION['user_id'])) { redirect('/login'); } $name = $_SESSION['user_name']; $noteFile = __DIR__ . '/user_data/note-' . $_SESSION['user_id'] . '.txt'; if ($isPost) { if (!is_dir(__DIR__ . '/user_data')) { mkdir(__DIR__ . '/user_data'); } file_put_contents($noteFile, $_POST['content'] ?? ''); redirect('/'); } $note = is_file($noteFile) ? file_get_contents($noteFile) : "Write a note, $name."; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Notes</title> </head> <body> <h1>Welcome, <?= htmlspecialchars($name) ?></h1> <form method="post" action="/"> <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>"> <label for="content">Your note</label><br> <textarea id="content" name="content" rows="8" cols="40"><?= htmlspecialchars($note) ?></textarea><br> <button type="submit">Save Changes</button> </form> <form method="post" action="/logout"> <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>"> <button type="submit">Logout</button> </form> </body> </html>The new code adds the
profilescope, so the UserInfo response includes the user's first and last name (given_nameandfamily_name). The callback stores the name in the session next to the user's Id. The notes page greets the user by name and stores each user's note in a separate file in theuser_datafolder, named after the user's Id. -
Run the app:
$ php -S localhost:3000 index.php -
Open the app at http://localhost:3000 and click Log in with FusionAuth .
-
Log in with the following credentials:
- Login:
richard@example.com - Password:
password
- Login:
-
In a separate private or incognito window, open the app at http://localhost:3000 and click Log in with FusionAuth .
-
Click Create an account and create an account using your personal email address, a password, your name, and your birthdate.
-
Edit and save your own note. Your name appears at the top of the page and in the default note text.
Your PHP app now provides unique notes for each user. Each user can independently edit and save their note. When a user saves a note, the app writes the note to a note-<id>.txt file in the user_data directory. To identify which note belongs to which user, compare the id in the file name with the id field in the user's Source tab in the Admin UI. Log out of the app before you open the Admin UI. Otherwise, FusionAuth single sign-on logs you in to the Admin UI as the app user, who doesn't have access to the Admin UI.
Summary#
In this QuickStart, FusionAuth handled login for your PHP app:
- The League OAuth 2.0 Client sent users to the FusionAuth login page and exchanged the authorization code for an access token, so the app never saw their passwords.
- The session check in
index.phpsent logged-out users to the login page instead of the notes page. - FusionAuth's UserInfo endpoint gave the app each user's unique Id and name. The app used the Id to keep each note separate and the name to greet the user.
- FusionAuth's self-service registration let new users create their own accounts, with no sign-up code in the app.
Next Steps#
This was a quick introduction to using FusionAuth for user authentication. To learn more about integrating FusionAuth with your product, see Get Started.
FusionAuth has many features (including Social Login, Single Sign-On, Passkeys, Multi-factor Authentication), most of which are free. This example app is a great starting point for learning about FusionAuth features.