> ## Documentation Index
> Fetch the complete documentation index at: https://docs-dev-docs-event-stream-action-templates.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# PHP：Auth0-PHPを使用して始める

> PHPアプリケーションにおいて、フリクションレスなログインおよびサインアップ体験を統合します。

export const AuthCodeBlock = ({filename, icon, language, highlight, children}) => {
  const [displayText, setDisplayText] = useState(children);
  const [copyText, setCopyText] = useState(children);
  const wrapperRef = React.useRef(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      if (!window.autorun || !window.rootStore) {
        return;
      }
      unsubscribe = window.autorun(() => {
        let processedChildrenForDisplay = children;
        let processedChildrenForCopy = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
          let displayValue = value;
          if (key === "{yourClientSecret}" && value !== "{yourClientSecret}") {
            displayValue = value.substring(0, 3) + "*****MASKED*****";
          }
          processedChildrenForDisplay = processedChildrenForDisplay.replaceAll(new RegExp(escapedKey, "g"), displayValue);
          processedChildrenForCopy = processedChildrenForCopy.replaceAll(new RegExp(escapedKey, "g"), value);
        }
        setDisplayText(processedChildrenForDisplay);
        setCopyText(processedChildrenForCopy);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  useEffect(() => {
    if (!wrapperRef.current) return;
    const originalWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
    let isOverriding = false;
    const handleClick = e => {
      const button = e.target.closest('[data-testid="copy-code-button"]');
      if (!button || !wrapperRef.current.contains(button)) return;
      isOverriding = true;
      navigator.clipboard.writeText = text => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
          return originalWriteText(copyText);
        }
        return originalWriteText(text);
      };
      setTimeout(() => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
        }
      }, 100);
    };
    const wrapper = wrapperRef.current;
    wrapper.addEventListener('click', handleClick, true);
    return () => {
      wrapper.removeEventListener('click', handleClick, true);
      if (navigator.clipboard.writeText !== originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
    };
  }, [copyText]);
  return <div ref={wrapperRef}>
      <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
        {displayText}
      </CodeBlock>
    </div>;
};

Auth0-PHP SDKはPHPアプリケーション内に統合され、シンプルなユーザーログインとサインアップを提供します。Facebook、Google、またはX（旧Twitter）のようなソーシャルIDプロバイダーやEntra IDなどのエンタープライズプロバイダーをサポートします。SDKは、Auth0の認証と管理エンドポイントにアクセスする便利な方法を提供します。

Auth0-PHPレポジトリは、オープンソースで、[GitHubにホストされています](https://github.com/auth0/auth0-PHP)。バグ報告、機能改善の提案、プル要求など、すべての貢献に感謝します。

## 要件

* PHP 7.4以上（8.0以上を推奨）
* [Composer](https://getcomposer.org/doc/00-intro.md)

## インストール

Auth0 PHP SDKのインストールには、PHPの標準依存関係管理ツールである[Composer](https://getcomposer.org/doc/00-intro.md#installation-linux-unix-macos)が必要です。Composerを使用すると、プロジェクトに必要な依存ライブラリを宣言し、それらを自動的にインストールできます。続ける前に、Composerがインストールされており、シェルからアクセス可能であることを確認してください。

次に、SDKをインストールするために、プロジェクトDirectoryから以下のシェルコマンドを実行します：

```php lines theme={null}
composer require auth0/auth0-php
```

これにより、プロジェクト内に`vendor`というサブフォルダが作成され、PHP SDKを使用するために必要なすべての依存関係がダウンロードされます。また、これにより、SDKがアプリケーションと連携するために必要な`vendor/autoload.php`ファイルも作成され、後でインポートします。

## はじめに

Auth0認証と<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=management-api" tip="Management API: 顧客が管理タスクを実行できるようにするための製品。" cta="用語集の表示">Management API</Tooltip>を使用するには、無料のAuth0アカウントとアプリケーションが必要です：

1. [auth0.com/signup](https://auth0.com/signup)に移動し、アカウントを作成します。
2. ダッシュボードに移動したら、**［Applications（アプリケーション）］**、そして **［Create Application（アプリケーションの作成）］** の順に移動します。
3. アプリケーションに名称をつけ、**［Regular Web Application（通常のWebアプリケーション）］**、そして **［Create（作成）］** の順に選択します。
4. 必要な資格情報に使用する **［Settings（設定）］** タブをクリックします。詳細については、[「アプリケーションの設定」](/docs/ja-jp/get-started/applications/application-settings)をお読みください。

## SDKを構成する

敏感なAuth0資格情報を保存および読み込むために、[環境変数](https://secure.php.net/manual/en/reserved.variables.environment.php)を使用するべきです。これにより、アプリケーションにそれらをハードコーディングする必要がなくなります。プロジェクトディレクトリのルートにアプリケーションの資格情報を保存するための`.env`ファイルを作成しましょう。

プロジェクトで環境変数を使用する最も簡単な方法は、[PHP Dotenv](https://github.com/josegonzalez/php-dotenv)のようなライブラリを使用して、ローカルの`.env`ファイルと組み合わせることです。`.env`ファイルを作成し（公開されないようにし、バージョン管理から除外されていることを確認してください）、以下の値を追加します：

export const codeExample = `# The URL of our Auth0 Tenant Domain.
# If we're using a Custom Domain, be sure to set this to that value instead.
AUTH0_DOMAIN='https://{yourDomain}'

# Our Auth0 application's Client ID.
AUTH0_CLIENT_ID='{yourClientId}'

# Our Auth0 application's Client Secret.
AUTH0_CLIENT_SECRET='{yourClientSecret}'

# A long secret value we'll use to encrypt session cookies. This can be generated using \`openssl rand -hex 32\` from our shell.
AUTH0_COOKIE_SECRET='SEE COMMENT ABOVE'

# The base URL of our application.
AUTH0_BASE_URL='http://127.0.0.1:3000'`;

<AuthCodeBlock children={codeExample} language="text" lines />

このファイルをバージョン管理にコミットしたり、安全でない方法で共有したりしてはいけません。内容は慎重に取り扱い、パスワードのように扱うべきです。PHPは`.env`ファイルをネイティブに読み込むことができないため、それを行うためのPHPライブラリをインストールする必要があります。このドキュメントでは、`vlucas/phpdotenv`を使用しますが、お好きな「dotenv」ライブラリを使用しても問題ありません。プロジェクトディレクトリから、以下のシェルコマンドを実行し、ライブラリをインストールします：

```bash lines theme={null}
composer require vlucas/phpdotenv
```

## SDKを初期化する

新しいPHPアプリケーション内でSDKのインスタンスを構成し、初期化する準備が整いました。このデモのために作業するPHPソースファイル`index.php`を作成し、以下のスニペットを使用して始めましょう。

```php lines theme={null}
<?php

// Import the Composer Autoloader to make the SDK classes accessible:
require 'vendor/autoload.php';

// Load our environment variables from the .env file:
(Dotenv\Dotenv::createImmutable(__DIR__))->load();

// Now instantiate the Auth0 class with our configuration:
$auth0 = new \Auth0\SDK\Auth0([
    'domain' => $_ENV['AUTH0_DOMAIN'],
    'clientId' => $_ENV['AUTH0_CLIENT_ID'],
    'clientSecret' => $_ENV['AUTH0_CLIENT_SECRET'],
    'cookieSecret' => $_ENV['AUTH0_COOKIE_SECRET']
]);
```

おめでとうございます。アプリケーションのセットアップが完了し、Auth0で使用する準備が整いました。これで、PHPクイックスタートの一つを使用してアプリケーション例を構築できます。必要に応じて、以下のクイックスタートに従って構築するアプリケーションのタイプを選択してください。

* [PHP Webアプリケーション](https://auth0.com/docs/quickstart/webapp/php/)
* [PHPバックエンドAPI](https://auth0.com/docs/quickstart/backend/php/)

## もっと詳しく

* [PHP：Auth0-PHPを使用したログイン、ログアウト、ユーザープロファイルの返送](/docs/ja-jp/libraries/auth0-php/auth0-php-basic-use)
* [PHP：Auth0-PHPでManagement APIを使用する](/docs/ja-jp/libraries/auth0-php/using-the-management-api-with-auth0-php)
* [PHP：Auth0-PHPを使用したJWT（JSON Web Token）の検証](/docs/ja-jp/libraries/auth0-php/validating-jwts-with-auth0-php)
* [PHPAuth0-PHP統合のトラブルシューティング](/docs/ja-jp/libraries/auth0-php/troubleshoot-auth0-php-library)
