PHP/Login Authentication/Login Form

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

A More Sophisticated Login Page

 
<?php
session_start();
if (isset($_POST["submit"])) {
  if ($_POST["user"] == "php5" && $_POST["pass"] == "iscool") {
    $_SESSION["username"] = $_POST["user"];
    if (isset($_GET["url"])) {
      $url = $_GET["url"];
    } else {
      $url = "index.php";
    }
    if (!isset($_COOKIE[session_name()])) {
      if (strstr($url, "?")) {
        header("Location: " . $url .
          "&" . session_name() . "=" . session_id());
      } else {
        header("Location: " . $url .
          "?" . session_name() . "=" . session_id());
      }
    } else {
      header("Location: " . $url);
    }
  }
}
?>
<html>
<head>
<title>User Authentication</title>
</head>
<body>
<form method="post">
<input type="text" name="user" /><br />
<input type="password" name="pass" /><br />
<input type="submit" name="submit" value="Login" />
</form>
</body>
</html>



A Simple Login Page

 
<?php
session_start();
if (isset($_POST["submit"])) {
  if ($_POST["user"] == "php5" && $_POST["pass"] == "iscool") {
    $_SESSION["username"] = $_POST["user"];
  }
}
?>
<html>
<head>
<title>User Authentication</title>
</head>
<body>
<?php
if (isset($_SESSION["username"])) {
  echo("You are logged in!");
} else {
?>
<form method="post">
<input type="text" name="user" /><br />
<input type="password" name="pass" /><br />
<input type="submit" name="submit" value="Login" />
</form>
<?php
}
?>
</body>
</html>



A Simple User Authentication Script

 
<html>
<head>
<title>User Authentication</title>
</head>
<body>
<?php
if (isset($_POST["user"]) && isset($_POST["pass"]) &&
  strtolower($_POST["user"]) == "shelley" && $_POST["pass"] == "deadline") {
?>
Welcome!
<?php
} else {
?>
Please log in!
<form method="post">
User name: <input type="text" name="user" /><br />
Password: <input type="password" name="pass" /><br />
<input type="submit" name="Login" />
</form>
<?php
}
?>
</body>
</html>



Hard code login Form

<HTML>
<BODY>
<FORM METHOD="POST" ACTION="LoginFormAction.php">
<H2>Login Page</H2>
<BR><BR>
User Name:
<BR><INPUT TYPE="TEXT" NAME="username" SIZE="16">
<BR><BR>
Password:
<BR><INPUT TYPE="PASSWORD" NAME="password" SIZE="16">
<BR><BR> <BR><BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>
<!-- LoginFormAction.php
<?php
$passwords = array("name1"   =>"pass1", 
                   "name2"   =>"pass2");
                   
if ($password == $passwords[$username]){
    setcookie("username", $username, time()+1200);
    echo "<H2>Access granted.</H2>";
}else{
    setcookie("username", "", time()-3600);
    echo "<H2>Invalid user name or password: access denied.</H2>";
}
?>
-->



Login form with Error Messages and Preserving User Input

<?php
function validate_user ($username, $password){
    return true;
}
   
// create empty array to store error messages
$errors = array();
$p =& $_POST;
   
if (count ($p) > 0){
     if (!isset ($p["username"]) || (trim ($p["username"]) == "")){
          $errors[] = "You must enter a username.";
     }elseif{ ((strlen ($p["username"]) < 8) || (ereg ("[^a-zA-Z0-9]", $p["username"]))){
          $errors[] = "You did not enter a valid username. Usernames must be
                      at least eight characters long and can only contain
                      letters and digits.";
     }
     
     if (!isset ($p["password"]) || (trim ($p["password"]) == "")){
          $errors[] = "You must enter a password.";
     }elseif ((strlen ($p["password"]) < 8) || (ereg ("[^[:alnum:][:punct:][:space:]]", $p["password"]))){
          $errors[] = "You did not enter a valid password. Passwords must be
                      at least eight characters long and can only contain
                      letters, digits, punctuation and spaces.";
     }
     
     if (count ($errors) == 0) {
          $r = validate_user ($p["username"], $p["password"]);
   
          if ($r == false){
               $errors[] = "Login failed. Username/password not found.";
          } else {
               print ("<html><head><title>Congratulations</title></head>
                      <body><h1>Congratulations!</h1><p>You logged in!</p>
                      </body></html>");
               exit;
          }
     }
}
?>
<html>
<head><title>Login Form</title></head>
<body>
<h1>Login Form</h1>
<?php
     if (count ($errors) > 0) {
          $n = count ($errors);
          for ($i = 0; $i < $n; $i++){
               print "<br /><font color="red">" . $errors[$i] . "</font>";
          }     
     }
?>
<form action="<?php print ($PHP_SELF); ?>" method="POST">
     <table>
     <tr><td>Username:</td>
     <td><input type="text" name="username" value="<?php if (isset ($p["username"])) print $p["username"]; ?>" /></td>
     </tr>
     <tr><td>Password:</td>
     <td><input type="text" name="password" value="<?php if (isset ($p["password"])) print $p["password"]; ?>" /></td>
     </tr>
     <tr><td colspan="2"><input type="submit" name="submit"></td></tr>
     </table>
     <input type="hidden" name="__process_form__" value="1" />
</form>
</body>
</html>



Log-In Page

 
<html>
 <head>
  <title>Log-In Page</title>
 </head>
 <body>
 Please enter your user details to log-in here...
 <form action = "authenticate.php" method = "post">
 Username:<br>
 <input type = "text" name = "username">
 <br><br>
 Password:<br>
 <input type = "text" name = "password">
 <br><br>
 <input type = "submit" value = "Log In">
 </form>
 </body>
</html>
File: authenticate.php

<?php
$username = $_POST["username"];
$password = $_POST["password"];
$self =     $_SERVER["PHP_SELF"];
$referer =  $_SERVER["HTTP_REFERER"];
if( ( !$username ) or ( !$password ) )
{ header( "Location:$referer" ); exit(); }
$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 where user_name=\"$username\" and password = password( \"$password\" )";
 
$rs = mysql_query( $sql, $conn ) or die( "Could not execute query" );
$num = mysql_numrows( $rs );
if( $num != 0 )
{ 
  $msg = "<h3>Welcome $username - your log-in succeeded!</h3>";
}
else
{
  header( "Location:$referer" ); exit(); 
}
?>
<html>
 <head>
  <title>Log-In Authenticated</title>
  </head>
  <body>
   <?php echo( $msg ); ?>
  </body>
</html>



Verifying a login cookie

 
<?php
unset($username);
if ($_COOKIE["login"]) {
    list($c_username,$cookie_hash) = split(",",$_COOKIE["login"]);
    if (md5($c_username.$secret_word) == $cookie_hash) {
        $username = $c_username;
    } else {
        print "You have sent a bad cookie.";
    }
}
if ($username) {
    print "Welcome, $username.";
} else {
    print "Welcome, anonymous user.";
}
?>



View guestbook

 
<html>
<head>
<title>View guestbook</title>
</head>
<body>
<h3>Latest 3 guestbook entries...</h3>
<?php
$rs = @mysql_connect( "localhost", "userName", "password" )or die( "Could not connect to MySQL" );
$rs = @mysql_select_db( "my_database" ) or die( "Could not select database" );
$sql = "select * from guestbook order by time desc limit 3";
$rs = @mysql_query( $sql ) or die( "Could not execute SQL query" );
while ( $row = mysql_fetch_array( $rs ) ) 
{
?>
<table>
<tr>
<td><b>Name:</b> <?php echo $row["name"]; ?></td>
<td><b>Email:</b> <a href="mailto:<?php echo $row["email"]; ?>">
           <?php echo $row["email"]; ?></a> </td><tr>
<tr><td colspan="2">
  <?php
  $datetime = $row["time"];
  $year = substr( $datetime, 0, 4 );
  $mon  = substr( $datetime, 4, 2 );
  $day  = substr( $datetime, 6, 2 );
  $hour = substr( $datetime, 8, 2 );
  $min  = substr( $datetime, 10, 2 );
  $sec  = substr( $datetime, 12, 2 );
  $orgdate = date("l F dS, Y h:i A",mktime( $hour, $min, $sec, $mon, $day, $year ) );
  ?>
Date: <?php echo $orgdate; ?></td></tr>
<tr><td colspan="2"><b>Comments:</b> <?php echo $row["comments"]; ?></td></tr>
</table>
<br>
<?php } ?>
</body>
</html>