Skip to content

Instantly share code, notes, and snippets.

@tournasdim
Created May 20, 2014 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tournasdim/cf8b673ae6decd76b535 to your computer and use it in GitHub Desktop.
Save tournasdim/cf8b673ae6decd76b535 to your computer and use it in GitHub Desktop.
Basic Authentication and Session Setup with Silex
<?php
use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
use Silex\Provider\SessionServiceProvider;
/* include the silex autoload */
require_once __DIR__.'/../vendor/autoload.php';
$app = new Application();
$app->register(new SessionServiceProvider());
$app->get('/login', function () use ($app) {
$username = $app['request']->server->get('PHP_AUTH_USER', false);
$password = $app['request']->server->get('PHP_AUTH_PW');
if ('admin' === $username && 'admin' === $password) {
$app['session']->set('user', array('username' => $username));
return $app->redirect('/account');
}
$response = new Response();
$response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', 'site_login'));
$response->setStatusCode(401, 'Please sign in.');
return $response;
});
$app->get('/account', function () use ($app) {
if (null === $user = $app['session']->get('user')) {
return $app->redirect('/login');
}
return "Welcome {$user['username']}!";
});
$app->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment