Skip to content

Instantly share code, notes, and snippets.

@jasny
Created May 9, 2012 17:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasny/2646894 to your computer and use it in GitHub Desktop.
Save jasny/2646894 to your computer and use it in GitHub Desktop.
Authentication without sessions in PHP
<?php
$secretword = "secret"; # Change this before use
$matches = null;
if (!empty($_REQUEST['AUTH']) && preg_match('/^(\w++):(\d++):(\w++)$/', $_REQUEST['AUTH'], $matches)) {
$username = str_rot13($matches[1]);
$time = (int)$matches[2];
$authhash = $matches[3];
$logged_in = md5($username . $time . $secretword) === $authhash && $time >= time() - 3000;
}
if (!empty($_REQUEST['dologin'])) {
// Authenticate here
$username = $_REQUEST['username'];
$logged_in = true;
}
if (!empty($logged_in)) {
$time = time();
$authhash = str_rot13($username) . ':' . $time . ':' . md5($username . $time . $secretword);
output_add_rewrite_var('AUTH', $authhash); # Using URL rewriting
//setcookie('AUTH', $authhash); # Could also be done with a cookie
}
?>
<?php if (empty($logged_in)): ?>
<form action="#" method="POST">
<input type="hidden" name="dologin" value="1" />
<div><label for="input-username">Username</label> <input type="text" id="input-username" name="username" value="<?= isset($username) ? $username : '' ?>" /></div>
<div><label for="input-username">Password</label> <input type="password" id="input-username" name="password" /></div>
<div><input type="submit" value="submit" /></div>
</form>
<? exit(); ?>
<? endif; ?>
<h1>Welcome <?= $username ?></h1>
<a href="<?=basename(__FILE__)?>" >A link</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment