Here is a single script for user authentication checking. With this script you will only need this page to authenticate users for your “members only sections” Most utilities like this like to use three pages. One for the username password form one for the authentication and one for the successful login page. If found that bulky so I whittled it down to one script.
I have not tested this script against a database let me know if you find an error with the script and I will make corrections.
[php]<?php
session_start();
ob_start();
function login () {
?>
Please login.
Username: | |
Password: |
|
<?php } if ($_COOKIE["auth"] == "1") { // Checks Session for an authorized cookie. ###################################################################################### # This is where you redirect or do other things for successful cookie authorization # ###################################################################################### echo "User Already Authenticated For This Session."; /************************************************************************************* This code is used at the top of pages that you would like to require user authentication on or "members only pages" session_start(); if ($_COOKIE["auth"] == "1") { $display_block = "
You are an authorized user.
"; } else { //redirect back to login form if not authorized header("Location: authenticate.php"); exit; } *************************************************************************************/ } else { if (!$_POST) { // Checks for empty forms on submission login (); } else { $username = $_POST['userLogin']; //sets post information to variables $password = $_POST['userPassword']; //sets post information to variables //connect to server and select database $mysqli = mysqli_connect("localhost", "joeuser", "somepass", "database"); //create and issue the query $sql = "SELECT * FROM auth_users WHERE username = '".$username."' AND password = PASSWORD('".$password."')"; $result = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli)); //get the number of rows in the result set; should be 1 if a match if (mysqli_num_rows($result) == 1) { setcookie("auth", "1", 0, "/", "yourdomain.com", 0); header("Location: authenticate.php"); } else { ?> <h2>The username and/or password you entered were incorrect.</h2>
<?php
login ();
}
}
}
?>[/php]