PDA

View Full Version : [TUT] PHP Usersystem - Part 1



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!';
}

Sluing
17-04-2009, 12:34 AM
Nice, might come in handy.

Invent
17-04-2009, 01:44 AM
First thing I've noticed straight away:



$str = crypt(trim($str,'abc'));
should be


$str = crypt(trim($str),'abc');
(in the config.php file).

Also, you're not kidding about the inefficiency, this code code could be shortened a lot and could also work a lot faster.

Fehm
17-04-2009, 09:14 AM
Im sure that using


session_destroy();

Is more than enough, instead of using
unset and all that lot?


And why would you need to start a session on the register form :S
xD!
Im still learning, so these arent slating your things , there for my own personal gain of knowledge!

iDenning
17-04-2009, 01:02 PM
Thanks for this!

Fehm
17-04-2009, 02:07 PM
sure you coiuld just use

$passecrpyt = md5($password);

To save all the

function encrypt($str) {
$str = crypt(trim($str,'abc'));
return $str;
}

that you did?

iDenning
17-04-2009, 02:43 PM
sure you coiuld just use

$passecrpyt = md5($password);

To save all the

function encrypt($str) {
$str = crypt(trim($str,'abc'));
return $str;
}

that you did?


Does it really matter?

Nether$
17-04-2009, 06:23 PM
My first reply in like a year lol!

// Connects to the database.$conn = mysql_connect('localhost',DB_USER,DB_PASS);$select = mysql_select_db(DB_NAME,$conn);
1. why localhost? not always the case, why not define DB_HOST??

2. make a file called functions_and_classes.php and require it!

3. Don't select *. Don't store password (even if it's encrypted) as variables ($_SESSION super).

4. Instead of $_SESSION, why not use DB sessions?

5. Contradiction on #4 but use $_SESSION['logoutKey']. Not needed here but it's standard practices. what it is is a randomly assigned key on login which is checked when the user logs out to ensure that it is not a robot or noob longing them out.

Great that people like you do this, it's the best way to teach people so +rep coming your way! (not sure what effect it'll have though!)

Invent
17-04-2009, 07:30 PM
4. Instead of $_SESSION, why not use DB sessions?

Where's the need in that?

Trigs
17-04-2009, 08:27 PM
First thing I've noticed straight away:



$str = crypt(trim($str,'abc'));
should be


$str = crypt(trim($str),'abc');
(in the config.php file).

Also, you're not kidding about the inefficiency, this code code could be shortened a lot and could also work a lot faster.

Oh sorry, that was a typo. Must have accidentally erased it when I was changing the salt. I'll fix it.


Im sure that using


session_destroy();

Is more than enough, instead of using
unset and all that lot?


And why would you need to start a session on the register form :S
xD!
Im still learning, so these arent slating your things , there for my own personal gain of knowledge!

I'm not sure about the session_destroy. And you're right about the register, I'll take it out.


sure you coiuld just use

$passecrpyt = md5($password);

To save all the

function encrypt($str) {
$str = crypt(trim($str,'abc'));
return $str;
}

that you did?



I'm pretty sure mine is harder to crack.


My first reply in like a year lol!

// Connects to the database.$conn = mysql_connect('localhost',DB_USER,DB_PASS);$select = mysql_select_db(DB_NAME,$conn);
1. why localhost? not always the case, why not define DB_HOST??

2. make a file called functions_and_classes.php and require it!

3. Don't select *. Don't store password (even if it's encrypted) as variables ($_SESSION super).

4. Instead of $_SESSION, why not use DB sessions?

5. Contradiction on #4 but use $_SESSION['logoutKey']. Not needed here but it's standard practices. what it is is a randomly assigned key on login which is checked when the user logs out to ensure that it is not a robot or noob longing them out.

Great that people like you do this, it's the best way to teach people so +rep coming your way! (not sure what effect it'll have though!)

1. Most of the time, it's localhost
2. I don't use any classes and theres only 2 functions anyways
3. Why not select *?

Trigs
20-04-2009, 08:06 PM
bump for above post.
Also, in what way can I make the code more efficient?

Jxhn
21-04-2009, 06:17 PM
function clean($str) {
$str = trim($str);
if(!mysql_real_escape_string()) {
$str = addslashes($str);
}
$str = strip_tags(htmlspecialchars($str));
return $str;
}

Security risk.

function clean($str) {
$str = trim($str);
if(!get_magic_quotes_gpc()) {
$str = addslashes($str);
}
$str = strip_tags(htmlspecialchars($str));
return $str;
}

Trigs
21-04-2009, 08:33 PM
That's what I originally had but Iszak told me it was pointless.

Iszak
22-04-2009, 05:48 AM
Erm? I don't remember telling you anything about that, I never use "!mysql_real_escape_string" I either use "function_exists" or "get_magic_quotes_gpc". Anyway most of my code uses strict checking too so I doubt it's me who said it.

Trigs
22-04-2009, 06:13 AM
You told me not to use magic_quotes_gpc or something.

Iszak
22-04-2009, 06:46 AM
I probably didn't tell you not to use it, but not to rely on it.

Want to hide these adverts? Register an account for free!