> ## Documentation Index
> Fetch the complete documentation index at: https://translations.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> Auth0-PHP SDK をインストールして設定し、Auth0 アプリケーションを作成して、ユーザー認証を開始するための PHP プロジェクトを準備します。

# Auth0-PHP を使って始める

export const ReleaseStageNotice = ({feature, stage, plans, contact, terms}) => {
  const stageTextMap = {
    "beta": "Beta",
    "ea": "早期アクセス"
  };
  const stageText = stageTextMap[stage] || "製品リリース段階";
  const prsLink = "/docs/troubleshoot/product-lifecycle/product-release-stages";
  const linkify = (text, url) => {
    return <a href={url} target="_blank" rel="noreferrer" class="link">{text}</a>;
  };
  const includeDetails = (plans, contact, terms) => {
    const hasDetails = terms || plans || contact;
    if (!hasDetails) return null;
    return <span data-as="p">
            {plans && <>この機能は{linkify(`${plans}プラン`, "https://auth0.com/pricing")}でご利用いただけます。 </>}
            {contact && "参加をご希望の場合は、" + contact + "までお問い合わせください。 "}
            {terms && <>この機能を使用することにより、Oktaの該当する無料トライアル規約および{linkify("Master Subscription Agreement", "https://www.okta.com/legal")}に同意したものとみなされます。</>}
        </span>;
  };
  return <Warning>
            <span data-as="p">
                <strong>{feature}機能は現在、{linkify(stageText, prsLink)}です。</strong>
            </span>

            {includeDetails(plans, contact, terms)}
        </Warning>;
};

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>;
};

<ReleaseStageNotice feature="Auth0 PHP SDK v9" stage="beta" />

Auth0-PHP SDK は PHP アプリケーションに統合でき、ユーザーのログインやサインアップをシンプルに実装できます。Facebook、Google、X などのソーシャル <Tooltip tip="アイデンティティプロバイダー（IdP）: デジタルアイデンティティを保存および管理するサービス。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=identity+providers">アイデンティティプロバイダー</Tooltip> に加え、Active Directory などのエンタープライズプロバイダーにも対応しています。また、この SDK には Auth0 の認証エンドポイントおよび Management エンドポイントにアクセスするための便利なメソッドも用意されています。

Auth0-PHP リポジトリはオープンソースで、[GitHub で公開されています](https://github.com/auth0/auth0-PHP)。バグ報告、機能強化の提案、プルリクエストなど、あらゆる貢献を歓迎しています。

<div id="requirements">
  ## 要件
</div>

* PHP 8.2 以降
* [Composer](https://getcomposer.org/doc/00-intro.md)
* PHP `mbstring` 拡張機能
* [PSR-18 HTTP Client](https://packagist.org/providers/psr/http-client-implementation) の実装
* [PSR-17 HTTP Factory](https://packagist.org/providers/psr/http-factory-implementation) の実装
* [PSR-7 HTTP Messages](https://packagist.org/providers/psr/http-message-implementation) の実装

<div id="installation">
  ## インストール
</div>

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

次に、SDK をインストールするため、プロジェクトのディレクトリ内で次のシェルコマンドを実行します。

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

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

<div id="get-started">
  ## はじめに
</div>

Auth0 の Authentication API と Management API を使用するには、無料の Auth0 アカウントとアプリケーションが必要です。

1. [auth0.com/signup](https://auth0.com/signup) にアクセスして、アカウントを作成します。
2. ダッシュボードに入ったら、**アプリケーション** に移動し、**Create Application** を選択します。
3. アプリケーションに名前を付けて **Regular Web Application** を選択し、**Create** をクリックします。
4. 以下で使用する必要な資格情報を確認するには、**設定** タブをクリックします。詳しくは、[アプリケーション設定](/docs/ja-jp/get-started/applications/application-settings) を参照してください。

<div id="configure-the-sdk">
  ## SDK を設定する
</div>

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

プロジェクトで環境変数を使う最も簡単な方法は、ローカルの `.env` ファイルとあわせて [PHP Dotenv](https://github.com/josegonzalez/php-dotenv) のようなライブラリを使うことです。`.env` ファイルを作成し (このファイルに外部からアクセスできないようにし、バージョン管理の対象外にしてください) 、次の値を追加します。

export const codeExample = `# Auth0 Tenant Domain の URL。
# カスタムドメインを使用している場合は、代わりにその値を必ず設定してください。
AUTH0_DOMAIN='{yourDomain}'

# Auth0 アプリケーションの Client ID。
AUTH0_CLIENT_ID='{yourClientId}'

# Auth0 アプリケーションの Client Secret。
AUTH0_CLIENT_SECRET='{yourClientSecret}'

# セッションクッキーの暗号化に使用する、十分に長い secret 値です。これはシェルで \`openssl rand -hex 32\` を使って生成できます。
AUTH0_COOKIE_SECRET='SEE COMMENT ABOVE'

# アプリケーションのベース URL。
AUTH0_BASE_URL='http://127.0.0.1:3000'`;

<AuthCodeBlock children={codeExample} language="php" />

このファイルは、絶対にバージョン管理にコミットしたり、安全でない方法で共有したりしないでください。内容は慎重に扱い、パスワードと同様に保護する必要があります。
PHP は標準では `.env` ファイルを読み込めないため、そのための PHP ライブラリをインストールする必要があります。このドキメントでは `vlucas/phpdotenv` を使用しますが、お好みの "dotenv" ライブラリであればどれでも利用できます。プロジェクトのディレクトリで、次のシェルコマンドを実行してライブラリをインストールしてください。

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

<div id="initialize-the-sdk">
  ## SDK を初期化する
</div>

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

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

// Composer AutoloaderをインポートしてSDKクラスにアクセスできるようにします:
require 'vendor/autoload.php';

// .envファイルから環境変数を読み込みます:
(Dotenv\Dotenv::createImmutable(__DIR__))->load();

// Auth0クラスを設定でインスタンス化します:
$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_BASE_URL` は、Auth0アプリケーションで設定したコールバックURLと完全に一致する必要があります。
    'redirectUri' => $_ENV['AUTH0_BASE_URL'],
]);
```

おめでとうございます。アプリケーションの設定が完了し、Auth0 ですぐに利用できるようになりました。次は、PHP Quickstarts のいずれかを使ってサンプルアプリケーションを作成できます。ニーズに合った Quickstart に沿って進めるには、作成したいアプリケーションの種類を選択してください。

* [PHP Web アプリケーション](/docs/ja-jp/quickstart/webapp/php/)
* [PHP Backend API](/docs/ja-jp/quickstart/backend/php/)

<div id="learn-more">
  ## 詳細情報
</div>

* [Login、Logout、ユーザープロファイルを管理する](/docs/ja-jp/libraries/auth0-php/auth0-php-basic-use)
* [Authentication API を使用する](/docs/ja-jp/libraries/auth0-php/using-the-authentication-api-with-auth0-php)
* [Management API を使用する](/docs/ja-jp/libraries/auth0-php/using-the-management-api-with-auth0-php)
* [JWT (JSON Web Tokens) を検証する](/docs/ja-jp/libraries/auth0-php/validating-jwts-with-auth0-php)
* [Auth0-PHP 連携のトラブルシューティング](/docs/ja-jp/libraries/auth0-php/troubleshoot-auth0-php-library)
