PHP code example of auth0 / auth0-php

1. Go to this page and download the library: Download auth0/auth0-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

auth0 / auth0-php example snippets


use Auth0\SDK\Auth0;
use Auth0\SDK\Configuration\SdkConfiguration;

$configuration = new SdkConfiguration(
    domain: 'Your Auth0 domain',
    clientId: 'Your Auth0 application client ID',
    clientSecret: 'Your Auth0 application client secret',
    cookieSecret: 'Your generated string',
);

$auth0 = new Auth0($configuration);

// getCredentials() returns null if the user is not authenticated.
$session = $auth0->getCredentials();

if (null === $session || $session->accessTokenExpired) {
    // Redirect to Auth0 to authenticate the user.
    header('Location: ' . $auth0->login());
    exit;
}

if (null !== $auth0->getExchangeParameters()) {
    $auth0->exchange();
}

print_r($auth0->getCredentials()?->user);

use Auth0\SDK\API\Authentication;
use Auth0\SDK\Configuration\SdkConfiguration;

$config = new SdkConfiguration(
    domain: 'your-tenant.auth0.com',
    clientId: 'YOUR_CLIENT_ID',
    clientSecret: 'YOUR_CLIENT_SECRET',
    redirectUri: 'http://localhost:3000/callback',
);

$auth = new Authentication($config);

// Get authorization URL for login
$loginUrl = $auth->getLoginLink(state: 'random-state-string');

// Exchange authorization code for tokens
$response = $auth->codeExchange(code: $_GET['code']);

// Get user profile with access token
$userInfo = $auth->userInfo(accessToken: $accessToken);

// Refresh an access token
$response = $auth->refreshToken(refreshToken: $refreshToken);

// Client credentials (M2M) authentication
$response = $auth->clientCredentials();

// Exchange an external or custom token for Auth0 tokens (RFC 8693)
$response = $auth->customTokenExchange(
    subjectToken: 'external-token-value',
    subjectTokenType: 'urn:acme:mcp-token',
);

// Get logout URL
$logoutUrl = $auth->getLogoutLink(returnTo: 'http://localhost:3000');

// Sign up a new user
$response = $auth->dbConnectionsSignup(
    email: '[email protected]',
    password: 'SecurePassword123!',
    connection: 'Username-Password-Authentication',
);

// Request password change email
$response = $auth->dbConnectionsChangePassword(
    email: '[email protected]',
    connection: 'Username-Password-Authentication',
);

use Auth0\SDK\API\Management\Wrapper\ManagementClient;
use Auth0\SDK\API\Management\Wrapper\ManagementClientOptions;

$client = new ManagementClient(new ManagementClientOptions(
    domain: 'your-tenant.auth0.com',
    token: 'YOUR_MGMT_TOKEN',
));

$users = $client->users->list();

$client = new ManagementClient(new ManagementClientOptions(
    domain: 'your-tenant.auth0.com',
    clientId: 'YOUR_CLIENT_ID',
    clientSecret: 'YOUR_CLIENT_SECRET',
));

// Tokens are fetched automatically on first API call and cached in memory.
// Expired tokens are re-fetched transparently.
$user = $client->users->get('auth0|123');

$client = new ManagementClient(new ManagementClientOptions(
    domain: 'your-tenant.auth0.com',
    clientId: 'YOUR_CLIENT_ID',
    clientSecret: 'YOUR_CLIENT_SECRET',
    audience: 'https://custom-audience.example.com/',
));

use Symfony\Component\Cache\Adapter\FilesystemAdapter;

$cache = new FilesystemAdapter(namespace: 'auth0', defaultLifetime: 0, directory: '/tmp/auth0-cache');

$client = new ManagementClient(new ManagementClientOptions(
    domain: 'your-tenant.auth0.com',
    clientId: 'YOUR_CLIENT_ID',
    clientSecret: 'YOUR_CLIENT_SECRET',
    tokenCache: $cache,
));

// First request fetches a token and stores it in the cache.
// Subsequent requests (even in different PHP processes) reuse the cached token.
$user = $client->users->get('auth0|123');

$client = new ManagementClient(new ManagementClientOptions(
    domain: 'your-tenant.auth0.com',
    tokenProvider: function (): string {
        // Fetch token from your own source (vault, database, etc.)
        return getTokenFromVault();
    },
));

use Auth0\SDK\API\Management\Exceptions\Auth0ApiException;
use Auth0\SDK\API\Management\Exceptions\Auth0Exception;

try {
    $response = $client->actions->create(...);
} catch (Auth0ApiException $e) {
    echo 'API Exception occurred: ' . $e->getMessage() . "\n";
    echo 'Status Code: ' . $e->getCode() . "\n";
    echo 'Response Body: ' . $e->getBody() . "\n";
    // Optionally, rethrow the exception or handle accordingly.
}

$items = $client->actions->list();

foreach ($items as $item) {
    var_dump($item);
}

foreach ($items->getPages() as $page) {
    foreach ($page->getItems() as $pageItem) {
        var_dump($pageItem);
    }
}

use Auth0\SDK\API\Management\Users\Requests\UpdateUserRequestContent;

// Constructor only: null properties are OMITTED from the request.
// This sends {"name": "Jane"} - email is not touched.
$request = new UpdateUserRequestContent([
    'name' => 'Jane',
    'nickname' => null,  // Omitted - nickname is not changed
]);

// Setter: null properties are INCLUDED in the request.
// This sends {"name": "Jane", "nickname": null} - nickname is cleared.
$request = new UpdateUserRequestContent(['name' => 'Jane']);
$request->setNickname(null);

$request = (new UpdateUserRequestContent())
    ->setName('Jane')
    ->setNickname(null)    // Will send null - clears nickname
    ->setUserMetadata(null); // Will send null - clears user_metadata

use Auth0\SDK\API\Management\Management;

// Using Guzzle
$customClient = new \GuzzleHttp\Client(['timeout' => 5.0]);

$client = new Management(token: '<token>', options: [
    'client' => $customClient,
]);

// Using Symfony HttpClient
$customClient = new \Symfony\Component\HttpClient\Psr18Client(
    \Symfony\Component\HttpClient\HttpClient::create(['timeout' => 5.0])
);

$client = new Management(token: '<token>', options: [
    'client' => $customClient,
]);

use Auth0\SDK\API\Management\Wrapper\ManagementClient;
use Auth0\SDK\API\Management\Wrapper\ManagementClientOptions;

$client = new ManagementClient(new ManagementClientOptions(
    domain: 'your-tenant.auth0.com',
    clientId: 'YOUR_CLIENT_ID',
    clientSecret: 'YOUR_CLIENT_SECRET',
    httpClient: $customClient,
));

$response = $client->actions->create(
    ...,
    options: [
        'maxRetries' => 0 // Override maxRetries at the request level
    ]
);

$response = $client->actions->create(
    ...,
    options: [
        'timeout' => 3.0 // Override timeout to 3 seconds
    ]
);

composer