First off you'll need your MySQL database. Mine only has 5 columns but you can have more if you want to. This bit of cause will create a database, "userauth", then create 5 columns named "ID" for the user count, "UID" for the user's unique id number, "Username" for the user's username, "Email" for their email, and "Password" for the password. Heres the SQL code to use.
CREATE DATABASE `userauth` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `userauth`; CREATE TABLE `users` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `UID` int(11) NOT NULL, `Username` text NOT NULL, `Email` text NOT NULL, `Password` text NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Now for the "sql.php". Really all this code does to connect to the databse. First will will create the variables for your MySQL server and user information, then it will connect to the server. Next it will select the database, in this case "userauth". This code get used in "log.php" and "reg.php" to access the database. Here it is
<?php
//sql.php
$server = "localhost"; //Your MySQL Server
$user = "root"; //Your MySQL username
$pass = "redere"; //Password
$conn = mysql_connect($server, $user, $pass); //Connect to ther serve
$db = mysql_select_db("userauth", $conn); //Select the database
if(!$db) { //If it can't select the database
echo "There was an error, sorry :(/>"; //Show an error message
exit(); //Cancel any more PHP scripts
}
?>
Next you want your login page, I named mine "login.php". First it checks for errors and shows them just in cause the user had been redirected back to this page due to an error loggin in. Then it has a field of username, password, a submit button, and a link to register. When the user hits "Login" it will go to "log.php" to execute the login.
<?php
//login.php
session_start(); //Start the session
if(isset($_SESSION['ERRMSG']) && is_array($_SESSION['ERRMSG']) && count($_SESSION['ERRMSG']) >0 ) { //If the error session exists
$err = "<table>"; //Start a table
foreach($_SESSION['ERRMSG'] as $msg) { //Get each error
$err .= "<tr><td>" . $msg . "</td></tr>"; //Write them to a variable
}
$err .= "</table>"; //Close the table
unset($_SESSION['ERRMSG']); //Delete the session
}
?>
<html>
<head>
<title>My Login Form</title>
</head>
<body>
<form action='log.php' method='post'>
<table align="center">
<tr>
<td><?php echo $err; ?></td>
</tr>
<tr>
<td>Username</td>
<td><input type='text' name='username'></td>
</tr>
<tr>
<td>Password</td>
<td><input type='password' name='password'></td>
</tr>
<tr>
<td><input type='submit' value='Login'></td>
<td><a href="register.php">Register</a></td>
</tr>
</table>
</form>
</body>
</html>
Next up, we'll do the script to login, mine is called "log.php", this one has a function that will clean the input to remove SQL injections that mess up your script. First it'll get the input from the form and fix it up then make sure it's right if it is it sends you to the members page if not, it sets the errors in a seesion to be read by the login page and send you there. Here it is.
<?php
include("sql.php"); //Connect to SQL
session_start(); //Start session for writing
function Fix($str) { //Clean the fields
$str = trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$errmsg = array(); //Array to store errors
$errflag = false; //Error flag
$username = Fix($_POST['username']); //Username
$password = Fix($_POST['password']); //Password
//Check Username
if($username == '') {
$errmsg[] = 'Username missing'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Check Password
if($password == '') {
$errmsg[] = 'Password missing'; //Error
$errflag = true; //Set flag so it says theres an error
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG'] = $errmsg; //Write errors
session_write_close(); //Close session
header("location: login.php"); //Rediect
exit(); //Block scripts
}
//Create SELECT query
$qry = "SELECT * FROM `users` WHERE `Username` = '$username' AND `Password` = '" . md5($password) . "'";
$result = mysql_query($qry);
//Check whether the query was successful or not
if(mysql_num_rows($result) == 1) {
while($row = mysql_fetch_assoc($result)) {
$_SESSION['UID'] = $row['UID']; //Retrieve the UID from the database and put it into a session
$_SESSION['USERNAME'] = $username; //Set the username as a session
session_write_close(); //Close the session
header("location: member.php"); //Redirect
}
} else {
$_SESSION['ERRMSG'] = "Invalid username or password"; //Error
session_write_close(); //Close the session
header("location: login.php"); //Rediect
exit(); //Block scripts
}
?>
Now for the register page, mine is "register.php". Almost the same thing as the login page only with more fields. And instead of a register link, this one has a link, back to login.php, to click if you already have an account.
<?php
//register.php
session_start(); //Start the session
if(isset($_SESSION['ERRMSG']) && is_array($_SESSION['ERRMSG']) && count($_SESSION['ERRMSG']) >0 ) { //If the error session exists
$err = "<table>"; //Start a table
foreach($_SESSION['ERRMSG'] as $msg) { //Get each error
$err .= "<tr><td>" . $msg . "</td></tr>"; //Write them to a variable
}
$err .= "</table>"; //Close the table
unset($_SESSION['ERRMSG']); //Delete the session
}
?>
<html>
<head>
<title>My Register Form</title>
</head>
<body>
<form action='reg.php' method='post'>
<table align="center">
<tr>
<td><?php echo $err; ?></td>
</tr>
<tr>
<td>Username</td>
<td><input type='text' name='username'></td>
</tr>
<tr>
<td>Email</td>
<td><input type='text' name='email'></td>
</tr>
<tr>
<td>Password</td>
<td><input type='password' name='password'></td>
</tr>
<tr>
<td>Repeat Password</td>
<td><input type='password' name='rpassword'></td>
</tr>
<tr>
<td><input type='submit' value='Register'></td>
<td><a href="login.php">I have an account</a></td>
</tr>
</table>
</form>
</body>
</html>
Next up is the register script, "reg.php". First this will include "sql.php" to connect to to database. Next it uses the same function that the login script uses to clean the input fields. Then it sets the variables for the errors that might occur. Then it will create another function to generate a unique id that has never been udes before. Next it retrieve the values from the register form and then cheack each one. These are pretty simple the only really special two are for the email, which makes sure it in the right format, and for the password and rpassword that makes sure that they are the same. Now the script will check to see if the username has been used before, if so it returns an error. And then it checks to see if the errflas is true, if so then it set an error session and returns to the register form. And lasty and most importantly the code to actually add the user into the database, the is pretty simple. The SQL code just syays which rows to insert data into, then the actual data. If it works then it writes a success message, if not it it shows an error.
<?php
//reg.php
include("sql.php"); //Connect to SQL
session_start(); //Start session for writing
function Fix($str) { //Clean the fields
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$errmsg = array(); //Array to store errors
$errflag = false; //Error flag
$UID = "12323543534523453451465685454"; //Unique ID
$username = Fix($_POST['username']); //Username
$email = $_POST['email']; //Email
$password = Fix($_POST['password']); //Password
$rpassword = Fix($_POST['rpassword']); //Repeted Password
//Check Username
if($username == '') {
$errmsg[] = 'Username missing'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Check Email
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) { //Make sure email is in the format: me@hi.com
$errmsg[] = 'Invalid Email'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Check Password
if($password == '') {
$errmsg[] = 'Password missing'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Check Repeated Password
if($rpassword == '') {
$errmsg[] = 'Repeated password missing'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Make sure passwords match
if(strcmp($password, $rpassword) != 0 ) {
$errmsg[] = 'Passwords do not match'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Make sure username is availible
if($username != '') {
$qry = "SELECT * FROM `users` WHERE `Username` = '$username'"; //MySQL query
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) { //If username is in use
$errmsg[] = 'Username already in use'; //Create error
$errflag = true; //Set flag so it says theres an error
}
mysql_free_result($result);
}
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG'] = $errmsg; //Write errors
session_write_close(); //Close session
header("location: register.php"); //Rediect
exit(); //Block scripts
}
//Create INSERT query
$qry = "INSERT INTO `userauth`.`users`(`UID`, `Username`, `Email`, `Password`) VALUES('$UID','$username','$email','" . md5($password) . "')";
$result = mysql_query($qry);
//Check whether the query was successful or not
if($result) {
echo "Thank you for registering, " . $username . ". Please login <a href=\"login.php\">Here</a>";
exit();
} else {
die("There was an error, try again later");
}
?>
Now we'll do the logout script to log the user out, duh. Really simple first starts the session for using the sessions, then destorys them UID and USERNAME sessions, then redirects back to the login page.
<?php
session_start();
unset($_SESSION['UID']);
unset($_SESSION['USERNAME']);
header("location: login.php");
?>
Lastly, "auth.php", the script you can use to make member-only pages, this simply checks to see if the session is set then checks it against the username and if it's a match then allows the user to view the page, if not they'll be asked to login. And just incase someone tried to hack the site by creating one of the sessions then it destorys both anyway.
<?php
include("sql.php");
session_start();
function Destroy() {
unset($_SESSION['UID']);
unset($_SESSION['USERNAME']);
header("location: login.php");
}
if(isset($_SESSION['UID']) && isset($_SESSION['USERNAME'])) {
$UID = $_SESSION['UID'];
$username = $_SESSION['USERNAME'];
$qry = mysql_query("SELECT * FROM `users` WHERE `UID` = '$UID' AND `Username` = '$username'");
if(mysql_num_rows($qry) != 1) { Destroy(); }
} else { Destroy(); }
?>
You can use this code like I have here on "member.php".
<?php include("auth.php"); ?>
You are allowed here. <a href="logout.php">Logout (<?php echo $_SESSION['USERNAME']; ?>)</a>
To make any page you want only accesible to members just use this one line of PHP
<?php include("auth.php"); ?>
And there you have it, a working login system with member-only pages, enjoy!
Hope you like it,
Daniel
Attached File(s)
-
tutorial.zip (4.75K)
Number of downloads: 1029






MultiQuote






|