Help - Search - Members - Calendar
Full Version: Member Registration And Login System
Zymic Webmaster Forums > Zymic Free Web Hosting > Tutorials
uncled1023
Hello all. I have come back from hiding to bring to you all another tutorial. This member system uses Mysql Databases, PHP, and COOKIES.

First thing we will want to do is create a database for our site. Go to your phpmyadmin, or whatever software your host is using to manage the mysql databases. Create a database with whatever name you want.

Next, we will create a table in our mysql database where we can store all our users info.

Copy the following code into the sql injection box in your phpmyadmin.
CODE
CREATE TABLE users (
id int(10) NOT NULL auto_increment,
username varchar(100),
password varchar(250),
regdate varchar(20),
email varchar(100),
website varchar(150),
location varchar(150),
show_email int(2) DEFAULT '0',
PRIMARY KEY(id))

This will create a new table called 'users' in your database.

Now, we will create the main configuration file that will allow us to connect to our database.

Create a new file and call it 'config.php' and put the following code into it and save.
CODE
<?php
$host = "localhost";
$db_username = "*****"; // Your database username
$db_pass = "*****"; // the password to your username
$db_name = "*****"; // the name of the database your 'users' table is in.
$connection = mysql_connect("$host","$db_username","$db_pass") or die ("Couldn't connect to server.");
$db = mysql_select_db("$db_name", $connection) or die("Couldn't select database.");

The above code will connect you to the server and will allow you to pull any information you want from any of the tables within the connected database.

Now that you have connected to the database, lets set some global variables for the users info and the site.

Insert the following code after the database connect code in your 'config.php' page.
CODE
// Website Variables
error_reporting (E_ALL ^ E_NOTICE);
$salt = "ZKd88lUhsk21"; // creates a salt value to better encrypt the users password
$mysql = mysql_query("SELECT * FROM users WHERE username='".safe($_COOKIE['username'])."' AND id='".safe($_COOKIE['id'])."' AND password='".safe($_COOKIE['password'])."'");
$row = mysql_fetch_array($mysql);
$registration_date = $row['regdate'];
$email = $row['email'];
$website = $row['website'];
$location = $row['location'];
$show_email = $row['show_email'];

That code pulls the data from the user that is currently logged in on that computer. Only if the computer has all 3 cookies will it withdraw the information.

Now, lets make sure the user is logged in. Insert the following into 'config.php'
CODE
$mysql = mysql_query("SELECT * FROM users WHERE username='".safe($_COOKIE['username'])."' AND id='".safe($_COOKIE['id'])."' AND password='".safe($_COOKIE['password'])."'");
$rows = mysql_num_rows($mysql);
if($rows != 1) {
$logged_in = 0;
} else {
$logged_in = 1;
}

This code checks to see if the users cookies are valid, and if so, sets the user as logged in. Otherwise, they are set as logged out. $logged_in will be our main variable to check to see if the user is logged in throughout the website.

Lets now create a php function that we will use later to validate any input that a user may input throughout the site.
CODE
function safe($input) {
    $valid_input = mysql_escape_string($input);
    return $valid_input;
}

This function gets the input that you want validated, and puts it through mysql_escape_string. This removes any bad characters that might be used for sql injection to hack your site. To use this function, all you need to do is type '$validate_input = safe($user_input);' where $input is the string you want validated, and $validated_input is the resulting clean string.

And now we are done with the 'config.php' file! If you have done the coding correctly, this should be what you have in your file.
CODE
<?php
$host = "localhost";
$db_username = "*****"; // Your database username
$db_pass = "*****"; // the password to your username
$db_name = "*****"; // the name of the database your 'users' table is in.
$connection = mysql_connect("$host","$db_username","$db_pass") or die ("Couldn't connect to server.");
$db = mysql_select_db("$db_name", $connection) or die("Couldn't select database.");
error_reporting (E_ALL ^ E_NOTICE);
$salt = "ZKd88lUhsk21"; // creates a salt value to better encrypt the users password
$mysql = mysql_query("SELECT * FROM users WHERE username='".safe($_COOKIE['username'])."' AND id='".safe($_COOKIE['id'])."' AND password='".safe($_COOKIE['password'])."'");
$row = mysql_fetch_array($mysql);
$registration_date = $row['regdate'];
$email = $row['email'];
$website = $row['website'];
$location = $row['location'];
$show_email = $row['show_email'];

$mysql = mysql_query("SELECT * FROM users WHERE username='".safe($_COOKIE['username'])."' AND id='".safe($_COOKIE['id'])."' AND password='".safe($_COOKIE['password'])."'");
$rows = mysql_num_rows($mysql);
if($rows != 1) {
$logged_in = 0;
} else {
$logged_in = 1;
}

function safe($input) {
    $valid_input = mysql_escape_string($input);
    return $valid_input;
}
?>


Now we will move onto the 'index.php' page. This will be our main page, but will be relatively short.

First, create a new php file, and call it 'index.php'. After you have done this, lets create the main "skeleton" of the page by adding in the normal html code that goes with any index page.
CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Your Website</title>
</head>
<body>
</body>
</html>


Now, at the VERY top of the page, you will want to include our 'config.php' page we made earlier, so we can access all the variables from it and the database connect script.
CODE
<?php include 'config.php'; ?>


Now that we have all our variables, we will want to make a nice page right? for now, lets just make some links and a message telling the person viewing the site what the site is about.

Add the following in between your <body> tags.
CODE
<?php
$page = strip_tags($_GET['id']);
$page = preg_replace("/[^a-zA-Z0-9_\s]/", "", $page);
if($page=='' || $page=='index' || $page=='config')
{
    ?>
    Hello!  Welcome to my site.<br />
    <?php
    if($logged_in==1)
    {
        ?>
        If you would like to leave, please <a href='/logout.php'>Logout</a>
        <?php
    }
    else
    {
        ?>
        If you are already a member, please <a href='/index.php?id=login'>Login</a>
        <?php
    }
}
else
{
    $filename = $page.".php";
    if(file_exists($filename)) {
        include ''.$page.'.php';
    }
}
?>

What this does is if you are on the main page, then it will show the welcome message. If 'id' equals anything else, it includes the php file with that value as the name of the file. For example, when id=example, the included file would be 'example.php'. This allows us to only have the websites theme on one page, allowing a much easier time editing it later on.

If you have coded it correctly, this is what the 'index.php' should look like.
CODE
<?php include 'config.php'; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Your Website</title>
</head>
<body>
<?php
$page = strip_tags($_GET['id']);
$page = preg_replace("/[^a-zA-Z0-9_\s]/", "", $page);
if($page=='' || $page=='index' || $page=='config')
{
    ?>
    Hello!  Welcome to my site.<br />
    If you want to join our site, please <a href='/index.php?id=register'>Register Here</a><br />
    <?php
    if($logged_in==1)
    {
        ?>
        If you would like to leave, please <a href='/logout.php'>Logout</a>
        <?php
    }
    else
    {
        ?>
        If you are already a member, please <a href='/index.php?id=login'>Login</a>
        <?php
    }
}
else
{
    $filename = "/".$page.".php";
        if(file_exists($filename)) {
    include ''.$page.'.php';
        }
}
?>
</body>
</html>


Now that you have your main page where people can enter your site, lets create the registration page so people can sign up for your site.

To start off, lets create a file called 'register.php'. Lets put the following code into it and i will explain what it does afterwards.
CODE
<?php
if (isset($_POST['submit'])) { // if form has been submitted
    /* check they filled in what they supposed to,
    passwords matched, username
    isn't already taken, etc. */
    if (!$_POST['uname'] || !$_POST['passwd'] ||
        !$_POST['passwd_again'] || !$_POST['email']) {
        die('You did not fill in a required field.');
    }
    //validate the inputs
    $_POST['uname'] = safe($_POST['uname']);
    $_POST['passwd'] = safe($_POST['passwd']);
    $_POST['email'] = safe($_POST['email']);
    $_POST['website'] = safe($_POST['website']);
    $_POST['location'] = safe($_POST['location']);
    // check if username exists in database.
    $qry = "SELECT username FROM users WHERE username = '".$_POST['uname']."'";
                $sqlmembers = mysql_query($qry);
                $name_check = mysql_fetch_array ($sqlmembers);
                $name_checkk = mysql_num_rows ($sqlmembers);
    if ($name_checkk != 0) {
        die('Sorry, the username: <strong>'.$_POST['uname'].'</strong>'
          . ' is already taken, please pick another one.');
    }
    // check passwords match
    if ($_POST['passwd'] != $_POST['passwd_again']) {
        die('Passwords did not match.');
    }
    // check e-mail format
    if (!preg_match("/.*@.*..*/", $_POST['email']) ||
         preg_match("/(<|>)/", $_POST['email'])) {
        die('Invalid e-mail address.');
    }
    // check show_email data
    if ($_POST['show_email'] != 0 & $_POST['show_email'] != 1) {
        die('Nope');
    }
    /* the rest of the information is optional, the only thing we need to
    check is if they submitted a website,
    and if so, check the format is ok. */
    
    // now we can add them to the database.
    // encrypt password
    $_POST['passwd'] = sha1($salt.$_POST['passwd']);
    $regdate = date('m d, Y');
    $insert = "INSERT INTO users (
            username,
            password,
            regdate,
            email,
            website,
            location,
            show_email)
            VALUES (
            '".$_POST['uname']."',
            '".$_POST['passwd']."',
            '$regdate',
            '".$_POST['email']."',
            '".$_POST['website']."',
            '".$_POST['location']."',
            '".$_POST['show_email']."')";

    $sqlmembers = mysql_query($insert);
?>
<h1>Registered</h1>
<p>Thank you, your information has been added to the database,
you may now <a href="login.php" title="Login">log in</a>.</p>
<?php
} else {    // if form hasn't been submitted
?>
<h1>Register</h1>
<form action="index.php?id=register" method="post">
<table align="center" border="1" cellspacing="0" cellpadding="3">
<tr><td>Username*:</td><td>
<input type="text" name="uname" maxlength="40">
</td></tr>
<tr><td>Password*:</td><td>
<input type="password" name="passwd" maxlength="50">
</td></tr>
<tr><td>Confirm Password*:</td><td>
<input type="password" name="passwd_again" maxlength="50">
</td></tr>
<tr><td>E-Mail*:</td><td>
<input type="text" name="email" maxlength="100">
</td></tr>
<tr><td>Website:</td><td>
<input type="text" name="website" maxlength="150">
</td></tr>
<tr><td>Location</td><td>
<input type="text" name="location" maxlength="150">
</td></tr>
<tr><td>Show E-Mail?</td><td>
<select name="show_email">
<option value="1" selected="selected">Yes</option>
<option value="0">No</option></select>
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Sign Up">
</td></tr>
</table>
</form>
<?php
}
?>

The above code shows the registration form. When the submit button is pressed, it refreshes the page and then it activates the code inside the submit part of the if/else function. This then validates the users input, displaying an error message for any errors recieved, and then posts the users information into the database and tells the user that the registration was successful.

Now that we have a main page, and registration page so users can register, lets give them a way to login into your site. Create a file called 'login.php' and put the following code into it.
CODE
<?php
if ($logged_in == 1) {  
    $query = "SELECT * FROM users WHERE username='".safe($_COOKIE['username'])."'";
       $sqlmembers = mysql_query($query);
    $number = mysql_fetch_array($sqlmembers);
    ?><br />
    Logged in as: <?php echo $_COOKIE['username']; ?><br />
    <br />
    <a href="/logout.php">Logout</a>
    <br /><br />
    <?php
}
else
{
?>
<form id="form1" name="form1" method="post" action="/process_login.php">
<h1>Login</h1>
<br />
        To login please fill in the form below.
        <p align="center">Username:
        <input type="text" name="uname" maxlength="40" />
        </p>
        <p align="center">Password:
        <input type="password" name="passwd" maxlength="50" />
        </p>
        <p align="center">Remember Me <input type="checkbox" name="logon_all" value="1" checked="yes" /></p>
        <center>
        <p>
        <input type="submit" name="submit" value="Login" />
        </p>
        </center>
        </form>
      <p>
      Don't have an account?  <a href="/index.php?id=register">Register for Free!</a>
      </p>
<?php
}
?>


This code checks to see if the user is logged in with the variable $logged_in, and displays the users info if he is logged in, otherwise it shows the login form, which when submitted, will post the data to a different page, which we will create now.

Make a new page called 'process_login.php'. This will be where we actually set the cookies for the user.
CODE
<?php
include 'config.php';
/* check they filled in what they were supposed to and authenticate */
if(!$_POST['uname'] || !$_POST['passwd']) {
echo "You have not entered all your information.";
} else {
// Replace bad characters //
$_POST['uname'] = safe($_POST['uname']);
$_POST['passwd'] = safe($_POST['passwd']);
$qry = "SELECT * FROM users WHERE username = '".$_POST['uname']."'";
$sqlmembers = mysql_query($qry);
$info = mysql_fetch_array($sqlmembers);
$check = mysql_num_rows($sqlmembers);
if ($check == 0) {
echo "The username you have given does not exist.  Please try again.";
} else {
// check passwords match
$_POST['passwd'] = stripslashes($_POST['passwd']);
$passwrd = sha1($salt.$_POST['passwd']);
if ($passwrd != $info['password']) {
echo "The password you entered was incorrect.";
} else {
// if we get here username and password are correct,
//register cookie variables.
$usr = mysql_query("SELECT * FROM users WHERE username = '".$_POST['uname']."'");
        $msga = mysql_fetch_array($usr);
        $ida = $msga['id'];

        if($_POST['logon_all'] == 1) {
        $expire=time()+60*60*24*15;
        setcookie("username", $_POST['uname'], $expire);
        
        $expire=time()+60*60*24*15;
        setcookie("id", $ida, $expire);
        
        $expire=time()+60*60*24*15;
        setcookie("password", $passwrd, $expire);

        } else {
        $expire=time()+60*60;
        setcookie("username", $_POST['uname'], $expire);
        
        $expire=time()+60*60;
        setcookie("id", $ida, $expire);
        
        $expire=time()+60*60;
        setcookie("password", $passwrd, $expire);
        
        }
?>
<script type="text/javascript">
<!--
window.location = "/index.php?id=profile"
//-->
</script>
<?php
}
}
}
?>

The above code will validate the inputed values, and check to see if they are correct for the given username. If both are correct, it will set the cookie variables with different time depending on if the user wanted to be remembered or not.

Now that the user can register, and login, lets give them the ability to logout. Create a file called 'logout.php'.
CODE
<?php
include 'config.php';    // database connect script.
if ($logged_in == 0) {
echo "You are not logged in, so you can not log out.";
}
else
{
setcookie("id", "", time()-6600);
setcookie("password", "", time()-6600);
setcookie("username", "", time()-6600);

header('Location: index.php');
}
?>


Ok, so your user can now register, login, logout, and be remembered if he is logged in on his next visit. Now what if you want to create a page that is only visable to a logged in user? We will create a new page that you will just need to include into the top of any page you want to proctect to ensure they can not view that page unless they are logged in.

Create a file called 'login_check.php' and put the following code into it.
CODE
<?php
if($logged_in == 0) {            
?>
<script type="text/javascript">
<!--
window.location = "/index.php?id=login"
//-->
</script>
<?php
}
?>

This will check to see if the user is logged in, and if not, redirect them to the login page. To protect any page, all you have to do is put the following code at the top of the page.
CODE
<?php include 'login_check.php'; ?>

That simple.

And there you have it, a simple member and registration system that can be outfitted for almost any website, and is easy to update and tweak to your hearts content. I will be updating this periodically with a members page and edit account.

If you want the source files created in this tutorial, you can download them here: http://www.megaupload.com/?d=A118J74X

If you want to see a working example, you can visit: Here

Hoped you enjoyed. smile.gif
uncled1023
Hello everyone, i have redone this tutorial with some cleaner coding, and better methods and securer systems.
guitarguy656
hey thanks for the tutorial its good nut i am getting no where with it sad.gif

heres my clan sites url http://www.o4l-clan.clanteam.com/

the idea of this is so members can login and register on the site ect..

but ive did the guide the way you have and made all the php files and uploaded all of php files to the root and made the database with the sli injection thingy

but on the bottom of the site it just gives me cant find login page (or register page for that matter) any help would be great i am new to this stuff

am using dreamweaver cs4

i think i was ment to edit some of the php to fit with my site but i didnt its the same as in the tutorial

thanks
uncled1023
what do you mean it says cant find login page?
guitarguy656
i tryed this tutorial and even got andrew on the irc chat too sort out alot of things in it such as host, user id ect..

but he called it poor php (his words not mine)

in the end i just pulled it from the site casue it wont work

thanks anyways
uncled1023
Ok, ill check out the coding and see what i can come up with.
uncled1023
Ok, found the error. Take out the following code from your register.php file. Its on line 81.
CODE
if ($_POST['website'] != '' & !preg_match("/^(http|ftp):///", $_POST['website'])) {
        $_POST['website'] = 'http://'.$_POST['website'];
    }


Also, i updated the process_login.php so copy the code from there again.
guitarguy656
thank you very much i will try and report back
guitarguy656
ok so far no different at all...

ive got an error at the top of the page and also were i placed the login/out bits

it say at the top cant find config.php yet i have checked its there in the root right beside the index.php

also in the config page is local host ment to be there after all my database and table are on the zymic sever so will i need the server ip instead?
uncled1023
um, keep it as localhost. That should not be changed. And, if it says can not find config.php, then it must not be in the same place as your index.php did you change the filename of config.php?
uncled1023
ok, code edited to work with zymic servers. Please let me know if you have any issues.
guitarguy656
thanks for the fix tongue.gif

it works a treat now !!!!!!!!!

just got to learn php a hell of a lot better sleep.gif

your help was very good considering its was just over the irc lol

now just to make it clan member friendly with posting options, a personal area for each member and sum other kool stuff

thanks again

uncled1023
no problem, glad to help. smile.gif
Casey2019
I added this to my page and everything works wonderfully, thank you for putting this up I've been looking for something like this for a long time. The only problem I have with it is that when I was testing the register page it just brings me right back to the index page and doesn't register anyone. If you could help out that would be awesome. Thank you.
I know a little bit about PHP and I alot about HTML but I cant seem to find a way to fix this.

QUOTE
<form action="index.php?id=register" method="post">


i've tried changing the index.php?id=register to <?php echo $_SERVER['PHP_SELF']?> so it would send the information to itself but that brought up an error saying

QUOTE
Fatal error: Call to undefined function safe() in /www/zzl.org/t/h/e/therealmofwonderers/htdocs/register.php on line 11


Thanks for the code still. It is amazing and better then anything I could ever dream of doing so thank you.

**EDIT**
Okay I got it all fixed, I just added include 'config.php'; to the top of the page and that worked. If thats not what i needed to do or if that will cause a security breach let me know. Again thank you for this code.
uncled1023
yep, if you dont have the register.php included in the index, where the config.php is included, then you need to include it on the page like you did.

woah, what happened to all the posts? ohmy.gif
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2010 Invision Power Services, Inc.