PHP/HTML/Authentication

Материал из Web эксперт
Перейти к: навигация, поиск

Authentication Over HTTP

   <source lang="html4strict">

<?

   if (!isset($_SERVER["PHP_AUTH_USER"])) {
           header("WWW-Authenticate: Basic realm=\"Private Area\"");
           header("HTTP/1.0 401 Unauthorized");
           print "Sorry - you need valid credentials granted access to the private area!\n";
           exit;
   } else {
           print "Welcome to the private area, {$_SERVER["PHP_AUTH_USER"]}- you used {$_SERVER["PHP_AUTH_PW"]} as your password.";
   }

?>

 </source>
   
  


Basic authentication prompt

   <source lang="html4strict">

<? header("WWW-Authenticate: Basic realm="Secret Family""); header("HTTP/1.0 401 Unauthorized"); exit; ?>

 </source>
   
  


Checking the values returned from the authentication prompt

   <source lang="html4strict">

<?php $username = "jon_doe"; $password = "JonDoe"; if (!isset($_SERVER["PHP_AUTH_USER"]) || !isset($_SERVER["PHP_AUTH_PW"])) {

   header("WWW-Authenticate: Basic realm="Member Area"");
   header("HTTP/1.0 401 Unauthorized");
   echo "You must enter in a username and password combination!";
   exit;

} elseif (strcmp($_SERVER["PHP_AUTH_USER"], $username) !== 0 ||

   strcmp($_SERVER["PHP_AUTH_PW"], $password) !== 0) {
   header("WWW-Authenticate: Basic realm="Member Area"");
   header("HTTP/1.0 401 Unauthorized");
   echo "Your username and password combination was incorrect!";
   exit;

} echo("You have successfully logged in!"); ?>

 </source>
   
  


Enforcing Basic authentication

   <source lang="html4strict">

<?php header("WWW-Authenticate: Basic realm="My Website""); header("HTTP/1.0 401 Unauthorized"); echo "You need to enter a valid username and password."; exit(); ?>

 </source>
   
  


Get Users from users table

   <source lang="html4strict">

<html><head><title>Get Users</title></head> <body> <?php $conn=@mysql_connect("localhost", "userName", "password") or die("Could not connect"); $rs = @mysql_select_db("my_database", $conn) or die("Could not select database");

$sql="select * from users";

$rs=mysql_query($sql,$conn) or die("Could not execute query");

$list = ""; $list.=""; $list.=""; $list.=""; $list.="";

while($row= mysql_fetch_array($rs) ) {

$list .= ""; $list .= ""; $list .= ""; $list .= ""; $list .= ""; $list .= ""; } $list .= "
First NameLast NameUser NamePassword
".$row["first_name"]."".$row["last_name"]."".$row["user_name"]."".$row["password"]."
";

echo($list); ?> </body></html>

 </source>
   
  


Hardcoding the username and password into a script

   <source lang="html4strict">

<? if ( (! isset ($PHP_AUTH_USER)) || (! isset ($PHP_AUTH_PW)) ||

  ($PHP_AUTH_USER != "secret") || ($PHP_AUTH_PW != "") ) :

    header("WWW-Authenticate: Basic realm="Secret Family"");
    header("HTTP/1.0 401 Unauthorized");
    print "Authorization is required.";
    exit;

endif; ?>

 </source>
   
  


HTTP Authentication example

   <source lang="html4strict">

<?php if(!isset($PHP_AUTH_USER)) {

   Header("WWW-Authenticate: Basic realm=\"My Realm\"");
   Header("HTTP/1.0 401 Unauthorized");
   echo "Text to send if user hits Cancel button\n";
   exit;

} else {

echo "Hello $PHP_AUTH_USER.

"; echo "You entered $PHP_AUTH_PW as your password.<P>"; } ?> </source>

HTTP Authentication example forcing a new name/password

   <source lang="html4strict">

<?php function authenticate() {

   Header( "WWW-authenticate: basic realm="Test System"");
   Header( "HTTP/1.0 401 Unauthorized");
   echo "You must enter a valid login ID and password to access this resource\n";
   exit;
   

} if(!isset($PHP_AUTH_USER) || ($SeenBefore == 1 && !strcmp($OldAuth, $PHP_AUTH_USER)) ) {

   authenticate();

} else {

   echo "Welcome: $PHP_AUTH_USER
"; echo "Old: $OldAuth"; echo "<FORM ACTION=\"$PHP_SELF\" METHOD=POST>\n"; echo "<INPUT TYPE=HIDDEN NAME=\"SeenBefore\" VALUE=\"1\">\n"; echo "<INPUT TYPE=HIDDEN NAME=\"OldAuth\" VALUE=\"$PHP_AUTH_USER\">\n"; echo "<INPUT TYPE=Submit VALUE=\"Re Authenticate\">\n"; echo "</FORM>\n";

} ?>

 </source>
   
  


If user logged in

   <source lang="html4strict">

<?php

 $user = $_POST["user"];
 $pass = $_POST["pass"];
 $self = $_SERVER["PHP_SELF"];
 if( ( $user != null ) and ( $pass != null ) )
 {
   setcookie( "auth","ok" );
   header( "Location:loggedin.php" );
   exit();
   }

?>

<html>

<head>
 <title>Set Cookie Data</title>
</head>
<body>
 <form action="<?php echo( $self ); ?>" method="post">
 Name: <input type="text" name="user" size="10">
 Password: <input type="text" name="pass" size="10">

<input type="submit" value="Log Me In"> </form> </body>

</html>

 </source>
   
  


Only One Username and Password Is Valid

   <source lang="html4strict">

<?php if (isset($_SERVER["PHP_AUTH_USER"])) {

 $user = $_SERVER["PHP_AUTH_USER"];
 $pass = $_SERVER["PHP_AUTH_PW"];

} elseif (isset($_SERVER["HTTP_AUTHORIZATION"])) {

 if (substr($_SERVER["HTTP_AUTHORIZATION"], 0, 5) == "Basic") {
   $userpass = split(":",
     base64_decode(substr($_SERVER["HTTP_AUTHORIZATION"], 6)));
   $user = $userpass[0];
   $pass = $userpass[1];  }

} if (!isset($user) || !isset($pass) || $user!="php5" || $pass!="iscool") {

 header("WWW-Authenticate: Basic realm=\"PHP Protected Area\"");
 header("HTTP/1.0 401 Unauthorized");

} else {

 echo("Welcome, $user!");

} ?>

 </source>
   
  


Simple credentials checking:

   <source lang="html4strict">

<?

   if (!isset($_SERVER["PHP_AUTH_USER"])) {
           header("WWW-Authenticate: Basic realm=\"Private Area\"");
           header("HTTP/1.0 401 Unauthorized");
           print "Sorry - you need valid credentials to be granted access!\n";
           exit;
   } else {
           if (($_SERVER["PHP_AUTH_USER"] == "A") &&
                   ($_SERVER["PHP_AUTH_PW"] == "B")) {
                   print "Welcome to the private area!";
           } else {
                   header("WWW-Authenticate: Basic realm=\"Private Area\"");
                   header("HTTP/1.0 401 Unauthorized");
                   print "Sorry - you need valid credentials to be granted access!\n";
                   exit;
           }
   }

?>

 </source>
   
  


The Username and Password Are Retrieved for Both Apache and IIS

   <source lang="html4strict">

<?php if (isset($_SERVER["PHP_AUTH_USER"])) {

 $user = $_SERVER["PHP_AUTH_USER"];
 $pass = $_SERVER["PHP_AUTH_PW"];

} elseif (isset($_SERVER["HTTP_AUTHORIZATION"])) {

 if (substr($_SERVER["HTTP_AUTHORIZATION"], 0, 5) == "Basic") {
   $userpass = split(":",
     base64_decode(substr($_SERVER["HTTP_AUTHORIZATION"], 6)));
   $user = $userpass[0];
   $pass = $userpass[1];
 }

} if (isset($user)) {

 echo("Username / password: ");
 echo(htmlspecialchars($user) . " / " . htmlspecialchars($pass));

} else {

 header("WWW-Authenticate: Basic realm=\"PHP Protected Area\"");
 header("HTTP/1.0 401 Unauthorized");

} ?>

 </source>
   
  


Use database to store user name and password

   <source lang="html4strict">

//login.html

   <form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
       Username:
<input type="text" name="username" size="10" />
Password:
<input type="password" name="pswd" SIZE="10" />
<input type="submit" value="Login" /> </form>

//index.php <?php

  session_start();
  if (! isset($_SESSION["name"])) {
     if (isset($_POST["username"])){
        $username = $_POST["username"];
        $pswd = $_POST["pswd"];
        $conn=pg_connect("host=localhost dbname=corporate user=root password=") or die(pg_last_error($conn));
        $query = "SELECT name FROM users WHERE username="$username" AND pswd="$pswd"";
        $result = pg_query($conn, $query);
        if (pg_num_rows($result) == 1){
           $_SESSION["name"] = pg_fetch_result($result,0,"name");
           $_SESSION["username"] = pg_fetch_result($result,0,"username");
           echo "You"re logged in. Feel free to return at a later time.";
        }
     } else {
        include "login.html";
     }
  } else {
      $name = $_SESSION["name"];
      echo "Welcome back, $name!";
   }

?>

 </source>
   
  


User management with database

   <source lang="html4strict">

create table user_info ( user_id char(18), fname char(15), email char(35)); <? if (! isset($userid)) :

    $id = "15";
    setcookie ("userid", $id, time()+3600);
    print "A cookie is set. Please refresh the page";

else:

    @mysql_connect("localhost", "root", "") or die("Could not connect to MySQL server!");
    @mysql_select_db("user") or die("Could not select user database!");
    $query = "SELECT * FROM user_info WHERE user_id = "$userid"";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    print "Hi ".$row["fname"].",
"; print "Your email address is ".$row["email"]; mysql_close();

endif; ?>

 </source>
   
  


Usernames and Passwords Are Checked Against Data in a Database

   <source lang="html4strict">

<?php if (isset($_SERVER["PHP_AUTH_USER"])) {

 $user = $_SERVER["PHP_AUTH_USER"];
 $pass = $_SERVER["PHP_AUTH_PW"];

} elseif (isset($_SERVER["HTTP_AUTHORIZATION"])) {

 if (substr($_SERVER["HTTP_AUTHORIZATION"], 0, 5) == "Basic") {
   $userpass = split(":",
     base64_decode(substr($_SERVER["HTTP_AUTHORIZATION"], 6)));
   $user = $userpass[0];
   $pass = $userpass[1];
 }

} $auth = false; $pwdb = mysql_connect("localhost", "user", "pwd"); mysql_select_db("auth", $pwdb); $rows = mysql_query("SELECT user, pass FROM users", $pwdb); while ($row = mysql_fetch_array($rows)) {

 if ($user == $row["user"] && crypt($pass, "pw") == $row["pass"]) {
   $auth = true;
   break;
 }

} if (!$auth) {

 header("WWW-Authenticate: Basic realm=\"PHP Protected Area\"");
 header("HTTP/1.0 401 Unauthorized");

} ?>

 </source>
   
  


Usernames and Passwords Are Checked Against Data in a File

   <source lang="html4strict">

<?php if (isset($_SERVER["PHP_AUTH_USER"])) {

 $user = $_SERVER["PHP_AUTH_USER"];
 $pass = $_SERVER["PHP_AUTH_PW"];

} elseif (isset($_SERVER["HTTP_AUTHORIZATION"])) {

 if (substr($_SERVER["HTTP_AUTHORIZATION"], 0, 5) == "Basic") {
   $userpass = split(":",
     base64_decode(substr($_SERVER["HTTP_AUTHORIZATION"], 6)));
   $user = $userpass[0];
   $pass = $userpass[1];
 }

} $auth = false; $pwfile = fopen("users.txt", "r"); while (!feof($pwfile)) {

 $data = split(":", rtrim(fgets($pwfile, 1024)));
 if ($user == $data[0] && crypt($pass, "pw") == $data[1]) {
   $auth = true;
   break;
 }

} fclose($pwfile); if (!$auth) {

 header("WWW-Authenticate: Basic realm=\"PHP\"");
 header("HTTP/1.0 401 Unauthorized");

} else {

 echo("Welcome, $user!");

} ?>

 </source>
   
  


Using HTTP authentication with a PHP script

   <source lang="html4strict">

<?php if (!isset($_SERVER["PHP_AUTH_USER"]) || !isset($_SERVER["PHP_AUTH_PW"])) {

   header("WWW-Authenticate: Basic realm="Member Area"");
   header("HTTP/1.0 401 Unauthorized");
   echo "Please login with a valid username and password.";
   exit;

} else {

  echo "You entered a username of: ".$_SERVER["PHP_AUTH_USER"]." ";
  echo "and a password of: ".$_SERVER["PHP_AUTH_PW"].".";

} ?>

</source>