Trigs
17-04-2009, 12:15 AM
I know this thread will end up in me being flamed but tuts have always helped me so I've decided to share. I know the code is horrible and inefficient but it's a tutorial. Also, the code loses it's formatting when I post it here so don't blame me.
Lets start with the heart of the usersystem, the configuration file.
config.php
<?php
// Defines the database information. Change to your own info.
define('DB_USER','');
define('DB_PASS','');
define('DB_NAME','');
// Connects to the database.
$conn = mysql_connect('localhost',DB_USER,DB_PASS);
$select = mysql_select_db(DB_NAME,$conn);
// This function creates a hash instead of storing passwords plaintext. Change abc to anything you want
function encrypt($str) {
$str = crypt(trim($str,'abc'));
return $str;
}
// This function strips input of any tags or special characters.
function clean($str) {
$str = trim($str);
if(!mysql_real_escape_string()) {
$str = addslashes($str);
}
$str = strip_tags(htmlspecialchars($str));
return $str;
}
// Checks to see if user is logged in.
if(isset($_SESSION['username']) && isset($_SESSION['password'])) {
$query = mysql_query("SELECT password FROM users WHERE username = '{$_SESSION['username']}'");
if(!$query || mysql_num_rows($query) < 1) {
unset($_SESSION['username']);
unset($_SESSION['password']);
$loggedin = false;
} else {
$loggedin = true;
}
} else {
$loggedin = false;
}
// Gets an array with the user's information in it.
$query = mysql_query("SELECT * FROM users WHERE username = '{$_SESSION['username']}'");
$users = mysql_fetch_array($query);
?>
Now let's add a way for users to register.
register.php
<?php
session_start();
// Loads the config file so we can use some stuff from it.
require_once 'config.php';
// Checks to see if the user is already logged in.
if($loggedin) {
die('You are already logged in.');
}
// If the user hasn't submitted the form
if(empty($_POST['register']) === false) {
// Create an array to store errors
$errors = array();
// Cleans the input and ecnrypts the password
$username = clean($_POST['username']);
$password = encrypt($_POST['password']);
// If they left a field empty
if(!$_POST['username'] || !$_POST['password']) {
$errors[] = 'You left a field blank';
}
// If the username they entered is longer than 30 characters.
if(strlen($username) > 30) {
$errors[] = 'Your username cannot exceed 30 characters.';
}
// Checks to see if the username is in the database
$query = mysql_query("SELECT username FROM users WHERE username = '$username'");
$count = mysql_num_rows($query);
// If the username is in the database, error them
if($count > 0 ) {
$errors[] = 'That username is already taken. Please choose another one.';
}
// Echos the errors.
if($errors) {
foreach($errors as $disperrors) {
echo $disperrors.'<br />';
}
echo 'Click <a href="register.php">here</a> to go back.'
die();
}
// If there are no errors, we can now add them to the database.
$query = mysql_query("INSERT INTO users (username , password) VALUES('$username' , '$password')");
// Success message
echo 'You have successfully registered, '.$username.'! You may now <a href="login.php">login</a>.';
// If they haven't submitted the form
} else {
echo '
<form method="post" action="">
Username: <br />
<input type="text" maxlength="30" name="username" /> <br /> <br />
Password: <br />
<input type="password" maxlength="30" name="password" /> <br /> <br />
<input type="submit" value="Register" name="register" />
</form>
';
}
?>
Now lets add the login part.
login.php
<?php
session_start();
// Loads the config file
require_once 'config.php';
// If the user is already logged them stop them from viewing the page.
if($loggedin) {
die('You are already logged in.');
}
// If they have submitted the form
if(empty($_POST['login']) === false) {
// Clean input and encrypt password
$username = clean($_POST['username']);
$password = encrypt($_POST['password']);
// If they left a field blank
if(!$_POST['username'] || !$_POST['password']) {
$errors[] = 'You left a field blank.';
}
// Checks to see if the username and password match.
$query = mysql_query("SELECT password FROM users WHERE username = '$username'");
// If the username doesn't exist, error them
if(!$query || mysql_num_rows($query) < 1) {
$errors[] = 'Username does not exist.';
}
// If the username/password is wrong, error them.
$login = mysql_fetch_array($query);
if($password != $login['password']) {
$errors[] = 'Wrong username/password.';
}
// If there are any errors, echo them.
if($errors) {
foreach($errors as $disperrors) {
echo $disperrors.'<br />';
}
echo 'Click <a href="login.php">here</a> to go back.'
die();
}
// Add the username and password to the session
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
// Success message if there are no errors.
echo 'Thanks for logging in. <a href="index.php">Main page</a>.';
// Otherwise echo form
} else {
echo '
<form method="post" action="">
Username: <br />
<input type="text" name="username" /> <br /> <br />
Password: <br />
<input type="password" name="password" /> <br /> <br />
<input type="submit" value="Login" name="login" />
</form>
';
}
?>
We also need a way to logout.
logout.php
<?php
session_start();
// Load configuration
require_once 'config.php';
// If the user isn't logged in, they can't logout.
if(!$loggedin) {
die('You need to be logged in to logout.');
} else {
// Gets rid of the session information
unset($_SESSION['username']);
unset($_SESSION['password']);
$_SESSION = array();
session_destroy();
// Lets them know they logged out.
echo 'You have successfully logged out.';
}
?>
And finally, you need the database info.
CREATE TABLE users (
id int(10) NOT NULL auto_increment primary key,
username varchar(30) NOT NULL,
password varchar(100) NOT NULL
);
To check if the user is logged in, use this:
if($loggedin) {
echo 'You are logged in!';
}
Lets start with the heart of the usersystem, the configuration file.
config.php
<?php
// Defines the database information. Change to your own info.
define('DB_USER','');
define('DB_PASS','');
define('DB_NAME','');
// Connects to the database.
$conn = mysql_connect('localhost',DB_USER,DB_PASS);
$select = mysql_select_db(DB_NAME,$conn);
// This function creates a hash instead of storing passwords plaintext. Change abc to anything you want
function encrypt($str) {
$str = crypt(trim($str,'abc'));
return $str;
}
// This function strips input of any tags or special characters.
function clean($str) {
$str = trim($str);
if(!mysql_real_escape_string()) {
$str = addslashes($str);
}
$str = strip_tags(htmlspecialchars($str));
return $str;
}
// Checks to see if user is logged in.
if(isset($_SESSION['username']) && isset($_SESSION['password'])) {
$query = mysql_query("SELECT password FROM users WHERE username = '{$_SESSION['username']}'");
if(!$query || mysql_num_rows($query) < 1) {
unset($_SESSION['username']);
unset($_SESSION['password']);
$loggedin = false;
} else {
$loggedin = true;
}
} else {
$loggedin = false;
}
// Gets an array with the user's information in it.
$query = mysql_query("SELECT * FROM users WHERE username = '{$_SESSION['username']}'");
$users = mysql_fetch_array($query);
?>
Now let's add a way for users to register.
register.php
<?php
session_start();
// Loads the config file so we can use some stuff from it.
require_once 'config.php';
// Checks to see if the user is already logged in.
if($loggedin) {
die('You are already logged in.');
}
// If the user hasn't submitted the form
if(empty($_POST['register']) === false) {
// Create an array to store errors
$errors = array();
// Cleans the input and ecnrypts the password
$username = clean($_POST['username']);
$password = encrypt($_POST['password']);
// If they left a field empty
if(!$_POST['username'] || !$_POST['password']) {
$errors[] = 'You left a field blank';
}
// If the username they entered is longer than 30 characters.
if(strlen($username) > 30) {
$errors[] = 'Your username cannot exceed 30 characters.';
}
// Checks to see if the username is in the database
$query = mysql_query("SELECT username FROM users WHERE username = '$username'");
$count = mysql_num_rows($query);
// If the username is in the database, error them
if($count > 0 ) {
$errors[] = 'That username is already taken. Please choose another one.';
}
// Echos the errors.
if($errors) {
foreach($errors as $disperrors) {
echo $disperrors.'<br />';
}
echo 'Click <a href="register.php">here</a> to go back.'
die();
}
// If there are no errors, we can now add them to the database.
$query = mysql_query("INSERT INTO users (username , password) VALUES('$username' , '$password')");
// Success message
echo 'You have successfully registered, '.$username.'! You may now <a href="login.php">login</a>.';
// If they haven't submitted the form
} else {
echo '
<form method="post" action="">
Username: <br />
<input type="text" maxlength="30" name="username" /> <br /> <br />
Password: <br />
<input type="password" maxlength="30" name="password" /> <br /> <br />
<input type="submit" value="Register" name="register" />
</form>
';
}
?>
Now lets add the login part.
login.php
<?php
session_start();
// Loads the config file
require_once 'config.php';
// If the user is already logged them stop them from viewing the page.
if($loggedin) {
die('You are already logged in.');
}
// If they have submitted the form
if(empty($_POST['login']) === false) {
// Clean input and encrypt password
$username = clean($_POST['username']);
$password = encrypt($_POST['password']);
// If they left a field blank
if(!$_POST['username'] || !$_POST['password']) {
$errors[] = 'You left a field blank.';
}
// Checks to see if the username and password match.
$query = mysql_query("SELECT password FROM users WHERE username = '$username'");
// If the username doesn't exist, error them
if(!$query || mysql_num_rows($query) < 1) {
$errors[] = 'Username does not exist.';
}
// If the username/password is wrong, error them.
$login = mysql_fetch_array($query);
if($password != $login['password']) {
$errors[] = 'Wrong username/password.';
}
// If there are any errors, echo them.
if($errors) {
foreach($errors as $disperrors) {
echo $disperrors.'<br />';
}
echo 'Click <a href="login.php">here</a> to go back.'
die();
}
// Add the username and password to the session
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
// Success message if there are no errors.
echo 'Thanks for logging in. <a href="index.php">Main page</a>.';
// Otherwise echo form
} else {
echo '
<form method="post" action="">
Username: <br />
<input type="text" name="username" /> <br /> <br />
Password: <br />
<input type="password" name="password" /> <br /> <br />
<input type="submit" value="Login" name="login" />
</form>
';
}
?>
We also need a way to logout.
logout.php
<?php
session_start();
// Load configuration
require_once 'config.php';
// If the user isn't logged in, they can't logout.
if(!$loggedin) {
die('You need to be logged in to logout.');
} else {
// Gets rid of the session information
unset($_SESSION['username']);
unset($_SESSION['password']);
$_SESSION = array();
session_destroy();
// Lets them know they logged out.
echo 'You have successfully logged out.';
}
?>
And finally, you need the database info.
CREATE TABLE users (
id int(10) NOT NULL auto_increment primary key,
username varchar(30) NOT NULL,
password varchar(100) NOT NULL
);
To check if the user is logged in, use this:
if($loggedin) {
echo 'You are logged in!';
}