Integrate authentication into PHP
This guide shows how to create a simple PHP application and secure it with authentication powered by Ory. The guide provides the setup for using Ory Network, but the code can be used with both Ory Network and self-hosted Ory software.
This guide is perfect for you if:
- You have PHP installed.
- You want to build an app using PHP.
- You want to give access to your application to signed-in users only.
Before you start, watch this video to see the user flow you're going to implement:
You can find the code of the sample application here.
Create PHP app
First we create a new PHP project:
mkdir your-project
cd your-project
touch index.php
Install dependencies
To interact with Ory's APIs we install the Ory SDK:
composer require ory/client
To simplify URLs handling we install the bramus/router
composer require bramus/router
Create a new Ory project
- Create an Ory account at https://console.ory.sh
- Create a new project at https://console.ory.sh/projects/create
- Go to your project settings
- Note down your project credentials (ID, slug, endpoint)
Install Ory CLI
To install Ory CLI follow this guide
Why do I need the Ory CLI
The Ory security model uses HTTP cookies to manage sessions, tokens, and cookies. Because of browser security measures like CORS, Ory APIs must be exposed on the same domain as your application.
In the case of this example the application runs on your local machine. The cookie domain is localhost
.
When developing locally, use either localhost
or 127.0.0.1
, but not both. Although technically these mean the same thing,
they're different cookie domains.
Using both interchangeably in your code causes problems, as Ory APIs will not receive the cookies when they are set on a different domain.
Ory CLI provides a convenient way to configure and manage projects. Additionally, the CLI provides Ory Proxy - a reverse proxy that rewrites cookies to match the domain your application is currently on.
To make Ory APIs and your application available on the same domain, Ory Proxy mirrors Ory endpoints and rewrites cookies to match the domain correct domain.
As a result, the domain of the cookies is set correctly to the domain you run the app on instead of
<your-project-slug>.projects.oryapis.com
.
By using the Proxy, you can easily connect the application you're developing locally to Ory Network and consume the APIs without additional configuration or the self-hosting any Ory services.
To learn more about the Ory Proxy, read the dedicated section of the Ory CLI documentation.
Create an Entry Page
Create a new file called index.php
and paste the following code:
<?php
require 'vendor/autoload.php';
require_once 'app.php';
error_reporting(E_ERROR | E_PARSE);
$proxyPort = getenv("PROXY_PORT");
if ($proxyPort == "") $proxyPort = "4000";
$app = new App;
// register a new Ory client with the URL set to the Ory CLI Proxy
// we can also read the URL from the env or a config file
$config = Ory\Client\Configuration::getDefaultConfiguration()->setHost(sprintf("http://localhost:%s/.ory", $proxyPort));
$app->ory = new Ory\Client\Api\FrontendApi(new GuzzleHttp\Client(), $config);
$router = new \Bramus\Router\Router();
$router->before('GET', '/', $app->validateSession());
$router->get('/', $app->printDashboard());
$router->run();
?>
This entry script creates an Ory client, registers new route for our Dashboard and makes use of Before Route Middlewares to validate if the user is allowed to view the Dashboard.
We are yet to create an App class, let's do that now.
Validate and login
Create a new file called app.php
and paste the following code:
<?php
class App
{
// save the session to display it on the dashboard
private ?Ory\Client\Model\Session $session;
public ?Ory\Client\Api\FrontendApi $ory;
public function validateSession()
{
$cookies = "";
// set the cookies on the ory client
foreach ($_COOKIE as $key => $value) {
$cookies .= "$key=$value;";
}
try {
// check if we have a session
$session = $this->ory->toSession("", $cookies);
if (! $session["active"]) throw new Exception('Session expired');
} catch (Exception $e) {
error_log('Exception when calling toSession: ' . $e->getMessage());
// this will initialize a new login flow and Kratos will redirect the user to the login UI
header("Location: /.ory/self-service/login/browser", true, 303);
die();
}
$this->session = $session;
}
public function printDashboard()
{
echo '
<html lang="en">
<head>
<title>Ory Network secured Go web app</title>
</head>
<body>
<h1>Dashboard</h1>
<hr />
<h2>Your Session Data:</h2>
<pre><code>', json_encode($this->session, JSON_PRETTY_PRINT), '</code></pre>
</body>
</html>
';
}
}
?>
Create a handler that checks with your Ory project to determine if the user has a valid session. We take the current request
cookies and pass them to the Ory client.
This file validates the session and redirects to the login page if the session is invalid. If the session is not valid, the request is redirected to the Ory project for login. At this stage, we have not set up any custom UI management, so the Ory Account Experience login page will be displayed.
Finally, we added the Dashboard handler (the page we want to protect), which will render HTML with the session data.
Run your app
Start your HTTP server and access the proxy URL
php -S 127.0.0.1:3000
Next open a new terminal window and start the Ory Proxy. Upon first start, the Ory Proxy will ask you to log into your Ory Console account.
ory proxy --project <PROJECT_ID> http://localhost:3000
To access the PHP app through the ORY proxy open http://localhost:4000 in your browser. You are presented with Ory's Sign In page. Let's click on sign up and create your first user.
Go to production
You can use many different approaches to go to production with your application. You can deploy it on Kubernetes, AWS, a VM, a
RaspberryPi - the choice is yours! To connect the application to your Ory project, the app and Ory APIs must be available under
the same common domain, for example https://ory.example.com
and https://www.example.com
.
You can easily connect Ory to your subdomain. To do that, add a Custom Domain to your Ory Network project.
With the custom domain set up, you don't need to use Ory Proxy or Ory Tunnel to interact with Ory APIs. Instead, use the configured custom domain in your SDK calls:
$config = Ory\Client\Configuration::getDefaultConfiguration()->setHost("https://ory.example.org"));
$ory = new Ory\Client\Api\FrontendApi(new GuzzleHttp\Client(), $config);