PHP/HTML/Authentication

Материал из Web эксперт
Версия от 07:05, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Authentication Over HTTP

 
<?
    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.";
    }
?>



Basic authentication prompt

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



Checking the values returned from the authentication prompt

 
<?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!");
?>



Enforcing Basic authentication

 
<?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();
?>



Get Users from users table

 
<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 = "<table>";
$list.="<tr><th>First Name</th>";
$list.="<th>Last Name</th>";
$list.="<th>User Name</th>";
$list.="<th>Password</th></tr>";
while($row= mysql_fetch_array($rs) )
{
   $list .= "<tr>";
   $list .= "<td>".$row["first_name"]."</td>";
   $list .= "<td>".$row["last_name"]."</td>";
   $list .= "<td>".$row["user_name"]."</td>";
   $list .= "<td>".$row["password"]."</td>";
   $list .= "</tr>";
}
$list .= "</table>";
echo($list);
?>
</body></html>



Hardcoding the username and password into a script

 
<?
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;
?>



HTTP Authentication example

 
<?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.<P>";
    echo "You entered $PHP_AUTH_PW as your password.<P>";
}
?>



HTTP Authentication example forcing a new name/password

 
<?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<BR>";
    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";
}
?>



If user logged in

 
<?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"><br><br>
  <input type="submit" value="Log Me In">
  </form>
 </body>
</html>



Only One Username and Password Is Valid

 
<?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!");
}
?>



Simple credentials checking:

 
<?
    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;
            }
    }
?>



The Username and Password Are Retrieved for Both Apache and IIS

 
<?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");
}
?>



Use database to store user name and password

 
//login.html
    <form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
        Username:<br /><input type="text" name="username" size="10" /><br />
        Password:<br /><input type="password" name="pswd" SIZE="10" /><br />
        <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!";
    }
?>



User management with database

 
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"].",<br>";
     print "Your email address is ".$row["email"];
     mysql_close();
endif;
?>



Usernames and Passwords Are Checked Against Data in a Database

 
<?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");
}
?>



Usernames and Passwords Are Checked Against Data in a File

 
<?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!");
}
?>



Using HTTP authentication with a PHP script

 
<?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"].".";
}
?>