Created
May 20, 2014 15:44
-
-
Save tournasdim/cf8b673ae6decd76b535 to your computer and use it in GitHub Desktop.
Basic Authentication and Session Setup with Silex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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