Welcome to Gaia! ::


6,600 Points
  • Invisibility 100
  • Elocutionist 200
  • Tycoon 200
Jahn(Thats Me!)
I remember when I first started coding, it was with basic HTML. I saw websites like neopets.com, and aftermathzone.com, and wondered "How do they do that?"
Well, 2 years later, I'm making my own pet sites. I thought I'd never get it... But I do. In your face Neopets! cool
Basically, almost all webpages these days with login and registration forms run with PHP and MySQL. In this tutorial, I will show you how they do it. =)
Before we start, make sure you have a database set up.

connect.php
<?php
// connect to the database
$link= @mysql_connect("localhost", "mysql_user", "mysql_password")

// select the database
$db= @mysql_select_db("your_database", $link)

// check to see if everything worked, @ before a function
// cancels the default error messages
if(!$link||!$db){
echo 'There seems to be an error. MySQL says:<br>'.mysql_error()}
?>

Okay, now we have the database connection. We need this at the top of every page that uses the function mysql_query, or any other MySQL related function. What this does is set up a direct link to the database, so PHP knows where all the queries go.



db.php
<?php
// connect to the db through "include"
include "connect.php";

// set the table and field names
$query= "CREATE TABLE users (
username VARCHAR(22) NOT NULL,
password VARCHAR(22) NOT NULL,
regdate VARCHAR(22) NOT NULL,
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id)
)";

// create the table
$run_query= @mysql_query($query)

// check if it worked
if(!$run_query){
echo 'There seems to be an error. MySQL says:<br>'.mysql_error()
}else{
echo 'Table was successfully added!';}
?>

This creates the table with 4 fields:
username, which is the users name. MAXLENGTH=22
password, which is the users password. MAXLENGTH=22
regdate, which is the users registration date. MAXLENGTH=22
id, which is the users identification number. Automatically set by MySQL.
Run this page before continuing any further.
REMEMBER TO DELETE THIS PAGE AFTER YOU RUN IT SO NO ONE HAS ACCESS TO IT, OR YOU DON'T ACCIDENTLY RESET THE TABLE!



register.php
<?php
// include the connection, see db.php
include "connect.php";

// check if the form was sent
if($_POST['sub']!=''){

// check if the fields are filled in
if($_POST['username']!=''&&$_POST['password']!=''&&$_POST['password2']!=''){

// check if the passwords match
if($_POST['password']==$_POST['password2']){

// check if the username is taken
// - set the query to select the info
// - from the db for checking it
$check_query= "SELECT * FROM users WHERE username='".$_POST['username']."'";

// - run the query
$check_run= mysql_query($check_query)

// - output results to an array
$array= mysql_fetch_array($check_run, MYSQL_ASSOC)

// - results can now be used, in this case, for
// - checking if the results are blank. this
// - signifies that there are no entries in the db
if($array["username"]==''){

// do the registration

// - set the date to $date
$date= date("m/d/y h:i:s")

// - set the query
$query= "INSERT INTO users (username, password, regdate)
VALUES('".$_POST['username']."', '".$_POST['password']."', '".$date."')";

// - add the user
$run_query= @mysql_query($query)

// - check if the registration was successful
if($run_query){
echo 'Congratulations, you are now a member!';
}else{
echo 'There seems to be an error. MySQL says:<br>'.mysql_error()}

// if the user already exists
}else{
echo 'There is already a user with that name, try adding numbers.';}

// if the passwords dont match
}else{
echo 'Your passwords don\'t match.';}

// if a field isn't set
}else{
echo 'There seems to be a field or two missing.';}

// if the form ISN'T sent
}else{

// display the form to register
echo '<form method="post" action="#doCreate">
Username:<br>
<input type="text" name="username" size=22 maxlength=22><br>
Password: <br>
<input type="password" name="password" size=22 maxlength=22><br>
Please confirm the password:<br>
<input type="password" name="password2" size=22 maxlength=22><br><br>
<input type="submit" name="sub" value="Register!">';}
?>

This is the registration page, this allows the user to register for your website. It also allows you to call the information thats submitted later on. It will check if the passwords match and if the fields are set, automatically. As an added bonus, it checks if the username is taken. =)



login.php
<?php
include "connect.php";
// if the form is sent
if($_POST['sub']!=''){

// if the fields are set
if($_POST['username']!=''&&$_POST['password']!=''){

// check the password

// - set the query to select the info
// - from the db for checking
$check_query= "SELECT * FROM users WHERE username='".$_POST['username']."'";

// - run the query
$check_run= mysql_query($check_query)

// - output results to an array
$array= mysql_fetch_array($check_run, MYSQL_ASSOC)

// check if user exists
if($array["username"]!=''){

// check if the passwords match
if($_POST['password']==$array["password"]){

// do login. we use cookies, because it is much easier than sessions

// - set username in $_COOKIE['username'] for 31 days
setcookie("username", $_POST['username'], time()+60*60*24*31)

// - set password in $_COOKIE['password'] for 31 days
setcookie("password", $_POST['password'], time()+60*60*24*31)

// - display welcome/success message
echo 'You are now logged in. Welcome!';

// if the password was wrong
}else{
echo 'Incorrect password. Feel free to try again.';}

// if the user doesn't exist
}else{
echo 'No such user in out database.';}

// if the fields weren't set
}else{
echo 'A field seems to be missing.';}

// if the form ISN'T sent
}else{

// display the form
echo '<form method="post" action="#doLogin">
Username:<br>
<input type="text" name="username" size=22><br>
Password:<br>
<input type="password" name="password" size=22><br><br>
<input type="submit" name="sub" value="Log-In!"></form>';}
?>

This is the login form, is displays an input for a username and password, then calls all info from the db to check the password and check if the user exists.



logout.php
<?php
// if the cookies aren't blank
if($_COOKIE['username']!=''&&$_COOKIE['password']!=''){

// unset both cookies
setcookie("username")
setcookie("password")

// output a message
echo 'Now logged-out. Bye bye!';

// if the cookies are blank
}else{
echo 'You have to be logged-in to log out.';}
?>

Probably the simplest script. =) If the cookies are set then delete them, otherwise, display an error.



setvars.php
<?php
// connect to db
include "connect.php";

// if the user is logged in
if($_COOKIE["username"]!=''&&$_COOKIE['password']!=''){
// set $loggein to 1 for future use
$loggedin= 1;

// set the query
$info_query= "SELECT * FROM users WHERE username='".$_COOKIE['username']."'";

// run the query
$info_run= mysql_query($info_query)

// output result to array
$info= mysql_fetch_array($info_run, MYSQL_ASSOC)

// if the user isn't logged in
}else{

// set $logged in to 0 for future use
$loggedin= 0;}

/*
These variables can now be used later on:

$info["username"]
$info["password"]
$info["regdate"]
$info["id"]
$loggedin


They contain:

The users username
The users password
The users date of registration
The users identification number
Whether the user is logged in or not, 1 if yes, 0 if no
*/
?>

This page should be included at the top of every page, this allows you to use special variables that contain the users information. See the comment in the /* */s for information. If you include this at the top of the page, connect.php isn't nessacary, as it is included in this page already.



examplepage.php
<?php
include "setvars.php";
// if the user is logged in
if($loggedin==1){

// output some text
echo 'Username:<br>'.$info["username"].'<br>Registered on:<br>'.$info["regdate"]

// if the user ISN'T logged in
}else{

// output an error
echo 'This page is for MEMBERS ONLY, please register in order to view this page.';}
?>

This is a sample page.



Heres another tip. Create two more pages entitled "head.php" and "foot.php" and put the top portion(all the html and coding before the actual content of the page) in "head.php" and the bottom portion(all the html and coding after the actual content of the page) in "foot.php" then include them on the top and bottom of the pages for an easy layout change. =)

Like this:
<?php include "head.php"; ?>
Content
<?php include "foot.php"; ?>




Best of luck,
Jahn =)




P.S. To see these scripts in action go to http://www.kokoropets.msshost.com/test/



If you see this tutorial anywhere but tutorialized.com, please tell me, so I can murder the user who posted it. =)

Please rate as well. Thanks. heart
Hey, code formatting User Image - Blocked by "Display Image" Settings. Click to show.

I have skimmed it, and it seems you hit the high point, and anyone who tutorializes what they have learned gets props.

I'll read it more thuroughly when I am less sleepy.

6,600 Points
  • Invisibility 100
  • Elocutionist 200
  • Tycoon 200
Foolish
Hey, code formatting User Image - Blocked by "Display Image" Settings. Click to show.

I have skimmed it, and it seems you hit the high point, and anyone who tutorializes what they have learned gets props.

I'll read it more thuroughly when I am less sleepy.

Heh, yeh I remembered. =3
Oh, and that code you gave me helped alot, thanks man. =)
This looks like a really good tutorial from what I've seen so far. I too, shall read more of it when I am not feeling so tired.
Hmm, this seems very useful to me. I just recently started playing around with PHP. I'll use this to help me learn more, thanks biggrin

Captain Kat's Husband

good stuff.

6,600 Points
  • Invisibility 100
  • Elocutionist 200
  • Tycoon 200
silver_wings_of_peace
good stuff.

Thanks. =3

@DarkFires: No problem. =)
@Colonel_Panic: Thanks. Took me a half an hour to write... gonk
@Foolish: You ******** rock man! =o
Hmm, so each of those scipt I will have to have in every HTML page on my website? I apologize, I'm still kinda new with PHP. And I really do not understand how to set up a MySQL data base (THe server I use is a bit confusing. 3nodding )
looks pretty solid, but just one comment.

generally speaking you should acquire your database connection at the last possible moment, then release it immediately.

in your code you include connect.php at the top of your script but only actually use your database connection after you've checked your post variables and cookie values.
This thread should be stickied. The only problem is finding a host who supports and allows SQL and PHP. Also wouldn't you have to start the script with a "<", or is that only for basic Html and Java?
Any paid host will allow PHP and MySQL. Also, if you set your own host up, it'll work too.

And i think all the scripts begin with a "<?", which is how you begin PHP.

6,600 Points
  • Invisibility 100
  • Elocutionist 200
  • Tycoon 200
fickness
looks pretty solid, but just one comment.

generally speaking you should acquire your database connection at the last possible moment, then release it immediately.

in your code you include connect.php at the top of your script but only actually use your database connection after you've checked your post variables and cookie values.

Yeh... But thats just to show how the system works. Remember, it's just a tutorial. =)

Oh, and being the moron that I am I forgot to include how to close the connection:
<?php
// This is how you close the link to MySQL
mysql_close($link)
?>

This is prefferably at the BOTTOM of every page you use. =)

And if your host doesn't support PHPMyAdmin then use this script to create databases:
<?php
// If the form was sent:
if($_POST['sub']!=''){

// Do the stuff

// Your MySQL username goes in this variable
$mysql_username= 'your_username';

// Your MySQL password goes in this variable
$mysql_password= 'your_password';

// The name of the database your creating goes
// in this variable. In this case, we get it from
// the variable sent by a form.
$mysql_db= $_POST['database']

// This part performs the "log-in" but in MySQL
// it's called a "connection" or a "link"
$link= mysql_connect('localhost', $mysql_username, $mysql_password)

// This will create the database and output a
// little warning and message for you.
// If it fails it prints the error and some
// possible reasons why it didn't work.
if(@mysql_create_db($mysql_db)){
echo 'Database created successfully.<br>
If MySQL says that "'.$mysql_db.'" isn't a database, try "'.$mysql_username.'_'.$mysql_db.'"';
}else{
echo 'Looks like the db creation failed. This can be for various reasons, some of which are:<br>
One: You already used all the databases that your host allows.<br>
Two: That username doesn\'t have proper permissions to create dbs.<br>
Three: A giant gorilla attacked MySQL and ate all the MySQL Pixies so they couldn\'t do there job. This is definetly the most likely.<br><br>
MySQL Says:<br>'.mysql_error()}

// If the form wasn't sent
}else{

// Then write the form. =)
echo '<form method="post" action="#doCreate">
<input type="text" name="database" size="22"><br>
<input type="submit" name="sub" value="Create It.">
</form>';}
?>

Let me know if the code works. I didn't get a chance to test it. I'm way to tired to do it right now. =s

6,600 Points
  • Invisibility 100
  • Elocutionist 200
  • Tycoon 200
UPDATE
Jahns next tutorial will most likely be on how to make a 100% PHP Based Web Host. So far, most web hosts are made with CGI, ASP, or some other non-PHP thing that I despise. This tutorial will include many scripts such as:
A custom File Editor/Creator
A script to view all files in a certain directory
A script to delete the files
A script to rename files
And a script to upload files from a users computer
I may even include a directory system. But don't get you hopes up, I'm not done with mine yet.

If you want an example of these scripts, or want me to write this tutorial, PM me.

-- This may take a while, I'm preoccupied with other stuff right now. =3
Why do you use cookies instead of sessions?
*Cough* SQL Injections Vulrabilities! *Cough*

You should to some type checking on your $_POST variables before you put them into a SQL query. If you don't people can wreak havok with your database.

Quick Reply

Submit
Manage Your Items
Other Stuff
Get GCash
Offers
Get Items
More Items
Where Everyone Hangs Out
Other Community Areas
Virtual Spaces
Fun Stuff
Gaia's Games
Mini-Games
Play with GCash
Play with Platinum