note 82565 added to features.http-auth

From: Date: Wed, 16 Apr 2008 16:21:22 +0000
Subject: note 82565 added to features.http-auth
Groups: php.notes 
Request: Send a blank email to php-notes+get-138376@lists.php.net to get a copy of this message
Here is my code for basic authentification login/logout. Include that code before any of your files: <?php function redirect_back($http=true, $html=true, $back=NULL){ if(is_null($back)){ if(isset($_REQUEST['referer'])){ $back = $_REQUEST['referer']; //}elseif(isset($_SERVER['HTTP_REFERER'])){ // $back = isset($_SERVER['HTTP_REFERER']); }else{ $back = "index.html"; } } if($http) header("Location: $back"); if($html){ $back = htmlspecialchars($back); print <<<EOF <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="refresh" content="0; url=$back"> </head> <body> <h1>HTTP/1.0 401 Unauthorized</h1> <p><a href="$back">Go back</a></p> </body> </html> EOF; exit(); } } $userid = 0; $username = false; if(isset($_SERVER['PHP_AUTH_USER']) and $_SERVER['PHP_AUTH_USER']){ $username = $_SERVER['PHP_AUTH_USER']; $userid = authenticate($username, $_SERVER['PHP_AUTH_PW']); if($userid===false) $username=false; // login failed } // If login succeeded (we have a username) or logout succeeded (no username) if(isset($_GET['login']) && $username || isset($_GET['logout']) && !$username){ // Go back redirect_back(); }elseif(isset($_GET['login']) || isset($_GET['logout'])){ // Ask for password header('WWW-Authenticate: Basic realm=""'); header('HTTP/1.0 401 Unauthorized'); redirect_back(false); } ?> You have to test of $username is not false if you want to be sure the user is authenticated. Example of use in HTML code: <?php if($username){ ?> <p>You are logged in with username <?php print htmlspecialchars($username); ?>.</p> <ul> <li><a href="?logout&amp;referer=<?php print htmlspecialchars(urlencode($_SERVER['PHP_SELF'])); ?>">logout</a></li> </ul> <?php }else{ ?> <p>You are anonymous.</p> <ul> <li><a href="?login&amp;referer=<?php print htmlspecialchars(urlencode($_SERVER['PHP_SELF'])); ?>">login</a></li> </ul> <?php } ?> ---- Server IP: 195.221.21.36 Probable Submitter: 2a01:5d8:52e9:601f:219:e3ff:fed8:18b ---- Manual Page -- http://www.php.net/manual/en/features.http-auth.php Edit -- https://master.php.net/note/edit/82565 Del: integrated -- https://master.php.net/note/delete/82565/integrated Del: useless -- https://master.php.net/note/delete/82565/useless Del: bad code -- https://master.php.net/note/delete/82565/bad+code Del: spam -- https://master.php.net/note/delete/82565/spam Del: non-english -- https://master.php.net/note/delete/82565/non-english Del: in docs -- https://master.php.net/note/delete/82565/in+docs Del: other reasons-- https://master.php.net/note/delete/82565 Reject -- https://master.php.net/note/reject/82565 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#138376) next »