Rikeku
09-18-2006, 03:31 PM
*** BASIC PHP USER SYSTEM ***
This tutorial aims to show you how to create a user system for your website which allows a user to register, login and logout in PHP. Also it’ll explain what each piece of code does in detail and why the code is needed. For this tutorial it’s better if you have a basic knowledge of PHP, HTML and MySQL (check out the resources at the bottom of the article). If you need a web host that offers PHP try www.100webspace.com, and for somewhere for your database www.freesql.org is a good site. Ok then let’s begin…
First things first we’re going to have to create our database. The amount of fields for the user data is up to you, you may want to hold a lot of data about the user you might not but in this tutorial the only fields for the database we need is:
- Username
- Password
- Email
- IP
If you are using FreeSQL.org then you can uses phpMyAdmin to create the database for you, if not you’ll have to do it with SQL statements. For example:
create table users
(username varchar(15),
password varchar(20),
email varchar(30),
ip varchar(20))
*** REGISTER.PHP ***
Ok so now we have our table. Now we need to make a script that allows a user to add their data. First we will create a PHP files that contains a form so that the users can sign up for your website. This file doesn’t contain any PHP code just an HTML form, the code doesn’t come until after this. We’ll call this file register.php.
<form action="register2.php" method="post">
Username: <input type="text" name="username" size="20">
Password: <input type="password" name="password" size="20">
Email: <input type="text" name="email" size="30">
<center><input type="submit"><input type="reset"></center>
</form>
OK so this is the form we’ll be adding to register.php so that a user can enter their data and sign up. If you have a good knowledge of HTML (which you probably will if your reading a tutorial on PHP) this should look pretty simple to you but for those who don’t I’ll explain.
<form action="register2.php" method="post">
This tag is just stating that there will be a form on the page. The action is the page which the POST variable collected by the form is sent to in order to be process and the method is just the way the form is getting the data, it can be either POST or GET.
Username: <input type="text" name="username" size="20">
Password: <input type="password" name="password" size="20">
Email: <input type="text" name="email" size="30">
This HTML is just adding the input boxes onto the page e.g. Username, Password and Email. The type will be text for the username and password fields but for the password the type password is used so that when the password is typed in the box it is hashed out. The name that you give these input boxes is what the POST variable will be called in the next page for example the post variables in register2.php will be:
- $_POST[‘username’]
- $_POST[‘password’]
- $_POST[‘email’]
These next two lines just adds a submit and reset button and tells the browser that the form is finished.
<center><input type="submit"><input type="reset"></center>
</form>
*** REGISTER2.PHP ***
Right then that’s our form finished and register.php finished, we will now move onto the PHP code in register2.php.
We will start our code by defining all of the variables we need for example the username and password the user entered into register.php.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$ip = $REMOTE_ADDR;
$username = strip_tags($username);
$email = strip_tags($email);
$password = md5($password);
In this section of code instead of having to type up the whole post variable e.g. $_POST[‘username’] we declare the variable $username, $password and $email as the post variables. This is not a necessity but I think it makes things easier. To get the IP of the user we use the global variable $REMOTE_ADDR.
Before adding the password to the database it must be hashed first so that if someone manages to steal the database information they have to crack the hash first before they log in as the user. This is very easy as PHP has the md5() function built into it, so after we have declared the variable password we must use the md5() function to hash it like below.
[code]
$password = md5($password);
Also before we add the information to the database we must make sure that we use the strip_tags() function to strip the PHP and HTML tags from the text as this could cause security issues. For example:
$username = strip_tags($username);
$email = strip_tags($email);
Now we have to check that the user has entered information for both the username and password fields by using an if statement as shown below:
if ( !$username || !$password ) {
die( "You did not enter a username or password" );
}
We use the ‘is not’ operator (!) to check if the $username and $password variables have anything assigned to them, if not the script is ended and the error message returned from the die() function is shown.
Now that we have declared all of the user information variables we can now move on to the SQL information variables. It would be easier to have the SQL information and connection settings in a separate php file for example database.php and use the include() function to add it to your script wherever you need it but in this tutorial I won’t be doing that.
Firstly we need to add the SQL username and password as well as the name of the database to variables like below:
$sqluser = “Test”;
$password = “Test”;
$db = “MyUsers”;
Now we need to connect to the MySQL database. To do this we will use the mysql_connect() function. Also we need to test for errors incase it can’t connect and to do this we will use an if statement. For example:
$connect = mysql_connect( "freesql.org", $sqluser, $sqlpass );
if ( ! $connect ) {
die( "Could not connect to SQL server" );
}
First of all we assign the connect function to the variable connect. Then to check if we can connect we use the if statement with the ! operator. The ! is a logical operator which means ‘is not’. So basically this code means if it can’t connect then use the die() function to stop running the code and display the error message “Could not connect to the SQL server. To read up on the operators in PHP there is a link to the w3schools website in the resources section.
Now we need to select the database so we will use the mysql_select_db() function. Also for the purpose of error checking we will use the die() function like previously and the mysql_error() function which returns an error message which explains how the error has occurred.
mysql_select_db( $db, $connect )
or die ("Could not open database:" .mysql_error() );
As you can see the mysql_select_db() function uses the two variables we defined earlier; $db which is the name of the database we want to select, and $connect which is the connection to the SQL server. The die() function here gives the message “Could not open database:” and the mysql_error() message afterwards if it comes across an error.
Now that we have got our connection settings finished and selected the database we want its now time to start writing the queries. If you don’t have much knowledge of SQL there is a tutorial in the resources section that is worth checking out.
OK to make sure there isn’t already someone in the database with the same username that the user has entered we need to use a SELECT statement which we will assign to the variable $selectstatement. For example:
$selectstatement = “SELECT * FROM yourtable WHERE username=’$username’”;
Where yourtable is replace it with the name of the table you store your user information in.
The next query we will need will be to insert the data into the database. For this we will be using the INSERT statement.
$insertstatement = “INSERT INTO users ( username, password, email, ip ) VALUES ( '$username', '$password', '$email', '$ip' )";
Now that we have our queries wrote and assigned to variables we will use the mysql_num_rows() function to see if anyone has the same username as the one the user specified in our form. We will use the SELECT statement we wrote earlier and pass it through the mysql_num_rows() function. The mysql_num_rows() function takes the result of a query and returns how many rows were returned. For example:
$selectresult = mysql_query( $selectstatement, $connect );
$numrows = mysql_num_rows( $result );
if ( $numrows > 0 ) {
print " The username you have chosen is in use. Please choose another one.";
}
By using the mysql_num_rows() we check to see if more that 0 records have been returned because if they have it means that someone in the database already has the username that they have chosen.
Now to finish off the code for register2.php we just have to add an else clause to the if statement above so it will look like this:
if ( $numrows > 0 ) {
print "The username you have chosen is in use. Please choose another one.";
} else {
mysql_query( $insertstatement, $connect )
or die( "Couldn't add data to table" );
print "Registration successful! Login <a href=\"login.php\">here</a>.";
}
?>
This just means that if all goes well and it passes through all the error checks that it passes the INSERT statement we wrote above through the mysql_query() function and prints the text “Registration successful!” and adds a link to the homepage to the webpage.
So now we have register2.php finished it’s time to move onto the login script.
*** LOGIN.PHP ***
For login.php we will only be using an HTML form no PHP so it should look like this:
<form method="POST" action="login2.php">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit" value="Login">
</form>
Once you have got the form on the login.php page like above it’s time to get onto the code in login2.php.
*** LOGIN2.PHP ***
Before we get into coding login2.php I’m first going to talk about session variables. In order for the website to know if the user is logged on and to remember they are after they have logged on we must start a session. A session gives the user a unique identifier which can be used to store information linked to that ID. For this to work on every page of your website you must start a session before any of the HTML or PHP. Also check the resources for a link about session variables. This code must be displayed at the top of your code on all of your pages:
<?php
session_start();
?>
Later on in the code I will talk more about the session variables and how we will use them but it is important to remember that that piece of code above must be before everything else in the code because if it is not it will not work.
Ok let’s start. Firstly we need to put the POST variables into easier to remember and shorter variable names like is register2.php. So the code will start like this:
<?php
$username = $_POST[‘username’];
$password = $_POST[‘password’];
Next since the password is stored in the database as an MD5 hash we need to use the md5() function that is built into PHP to hash the password. For example:
$password = md5($password);
Now we need to check to make sure that the user has entered data into both the username and password fields. This is done like below:
if ( (!$username) || (!$password) ) {
die(“You did not enter all of the needed information”);
}
This uses the ! operator that we have used previously to check if the $username and $password variables are empty and then if they are performs a die() function which stops running the code and displays an error message. The || operator we use here means OR. Check out the link in the resources section to read up more on the operators used in PHP as they are important.
Now that we’ve done that we need to add our code to connect to the MySQL database like we did in register2.php. Since I’ve more or less explained it already I’ll just add the code below:
[code]
$sqluser = “Test”;
$password = “Test”;
$db = “MyUsers”;
$connect = mysql_connect( "freesql.org", $sqluser, $sqlpass );
if ( ! $connect ) {
die( "Could not connect to SQL server" );
}
mysql_select_db( $db, $connect )
or die ("Could not open database:" .mysql_error() );
OK so now we have everything we need to connect to the database we need to write our query:
$selectstatement = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
To see if the user has entered the right password we need to use the mysql_num_rows() function. This is because the SELECT statement above will return more than 0 rows if the user has entered the correct information so we will use an if statement to finish off the code for login2.php as shown below:
$numrows = mysql_num_rows( $selectstatement );
if ( $numrows > 0 ) {
print “Login successful!”;
$_SESSION[‘username’] = $username;
$_SESSION[‘logged_in’] = “yes”;
} else {
print “Wrong username or password!”;
}
?>
As you can see if the user logs in successfully they get the message “Login successful!” and two session variables are defined. As long as the session_start() function I talked about previously is at the top of all your pages they will be remembered so you can use them on different pages.
You can use these session variables to see if a user is logged on. For example if there was a page on your website that you must be logged in to view you could use some code like this:
if ( $_SESSION[‘logged_in’] = “” ) {
print “You are not authorised to view this page”;
} else {
*** your code here ***
}
This code checks to see if the $_SESSION[‘logged_in’] variable is empty and if it is it displays an error message.
A use of the $_SESSION[‘username’] variable could be to display the users name on the website. For example:
if ( $_SESSION[‘username’] = “” ) {
print “You are not logged in!”;
} else {
print “Welcome $_SESSION[‘username’]!”;
}
Ok that’s it for login2.php and the user system is nearly ready, all we need to do now is write a script so the user can log out.
*** LOGOUT.PHP ***
This is only a few lines of code so here it is and I’ll explain after:
<?php
if ( $_SESSION['logged_in'] = “” ) {
echo "You are already logged out!";
} else {
session_destroy();
echo "You are now logged out.";
}
?>
Here we use the session variables we defined earlier again. The if statement checks that if the variable $_SESSION[‘logged_in’] is empty that it tells the user that they are already logged out. If not it uses the session_destroy() function that destroys the session and gives the user the message “You are now logged out”.
Ok so that’s the user system finished and if your ready it I hope it has been a help. If there any questions or problems with it just leave a comment and I’ll try to get an answer back to you.
-Rikeku
*** RESOURCES ***
PHP Operators: http://www.w3schools.com/php/php_operators.asp
Basic SQL: http://www.baycongroup.com/basic_sql_commands.htm
PHP Sessions: http://www.htmlgoodies.com/beyond/php/article.php/3472581
***
This tutorial aims to show you how to create a user system for your website which allows a user to register, login and logout in PHP. Also it’ll explain what each piece of code does in detail and why the code is needed. For this tutorial it’s better if you have a basic knowledge of PHP, HTML and MySQL (check out the resources at the bottom of the article). If you need a web host that offers PHP try www.100webspace.com, and for somewhere for your database www.freesql.org is a good site. Ok then let’s begin…
First things first we’re going to have to create our database. The amount of fields for the user data is up to you, you may want to hold a lot of data about the user you might not but in this tutorial the only fields for the database we need is:
- Username
- Password
- IP
If you are using FreeSQL.org then you can uses phpMyAdmin to create the database for you, if not you’ll have to do it with SQL statements. For example:
create table users
(username varchar(15),
password varchar(20),
email varchar(30),
ip varchar(20))
*** REGISTER.PHP ***
Ok so now we have our table. Now we need to make a script that allows a user to add their data. First we will create a PHP files that contains a form so that the users can sign up for your website. This file doesn’t contain any PHP code just an HTML form, the code doesn’t come until after this. We’ll call this file register.php.
<form action="register2.php" method="post">
Username: <input type="text" name="username" size="20">
Password: <input type="password" name="password" size="20">
Email: <input type="text" name="email" size="30">
<center><input type="submit"><input type="reset"></center>
</form>
OK so this is the form we’ll be adding to register.php so that a user can enter their data and sign up. If you have a good knowledge of HTML (which you probably will if your reading a tutorial on PHP) this should look pretty simple to you but for those who don’t I’ll explain.
<form action="register2.php" method="post">
This tag is just stating that there will be a form on the page. The action is the page which the POST variable collected by the form is sent to in order to be process and the method is just the way the form is getting the data, it can be either POST or GET.
Username: <input type="text" name="username" size="20">
Password: <input type="password" name="password" size="20">
Email: <input type="text" name="email" size="30">
This HTML is just adding the input boxes onto the page e.g. Username, Password and Email. The type will be text for the username and password fields but for the password the type password is used so that when the password is typed in the box it is hashed out. The name that you give these input boxes is what the POST variable will be called in the next page for example the post variables in register2.php will be:
- $_POST[‘username’]
- $_POST[‘password’]
- $_POST[‘email’]
These next two lines just adds a submit and reset button and tells the browser that the form is finished.
<center><input type="submit"><input type="reset"></center>
</form>
*** REGISTER2.PHP ***
Right then that’s our form finished and register.php finished, we will now move onto the PHP code in register2.php.
We will start our code by defining all of the variables we need for example the username and password the user entered into register.php.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$ip = $REMOTE_ADDR;
$username = strip_tags($username);
$email = strip_tags($email);
$password = md5($password);
In this section of code instead of having to type up the whole post variable e.g. $_POST[‘username’] we declare the variable $username, $password and $email as the post variables. This is not a necessity but I think it makes things easier. To get the IP of the user we use the global variable $REMOTE_ADDR.
Before adding the password to the database it must be hashed first so that if someone manages to steal the database information they have to crack the hash first before they log in as the user. This is very easy as PHP has the md5() function built into it, so after we have declared the variable password we must use the md5() function to hash it like below.
[code]
$password = md5($password);
Also before we add the information to the database we must make sure that we use the strip_tags() function to strip the PHP and HTML tags from the text as this could cause security issues. For example:
$username = strip_tags($username);
$email = strip_tags($email);
Now we have to check that the user has entered information for both the username and password fields by using an if statement as shown below:
if ( !$username || !$password ) {
die( "You did not enter a username or password" );
}
We use the ‘is not’ operator (!) to check if the $username and $password variables have anything assigned to them, if not the script is ended and the error message returned from the die() function is shown.
Now that we have declared all of the user information variables we can now move on to the SQL information variables. It would be easier to have the SQL information and connection settings in a separate php file for example database.php and use the include() function to add it to your script wherever you need it but in this tutorial I won’t be doing that.
Firstly we need to add the SQL username and password as well as the name of the database to variables like below:
$sqluser = “Test”;
$password = “Test”;
$db = “MyUsers”;
Now we need to connect to the MySQL database. To do this we will use the mysql_connect() function. Also we need to test for errors incase it can’t connect and to do this we will use an if statement. For example:
$connect = mysql_connect( "freesql.org", $sqluser, $sqlpass );
if ( ! $connect ) {
die( "Could not connect to SQL server" );
}
First of all we assign the connect function to the variable connect. Then to check if we can connect we use the if statement with the ! operator. The ! is a logical operator which means ‘is not’. So basically this code means if it can’t connect then use the die() function to stop running the code and display the error message “Could not connect to the SQL server. To read up on the operators in PHP there is a link to the w3schools website in the resources section.
Now we need to select the database so we will use the mysql_select_db() function. Also for the purpose of error checking we will use the die() function like previously and the mysql_error() function which returns an error message which explains how the error has occurred.
mysql_select_db( $db, $connect )
or die ("Could not open database:" .mysql_error() );
As you can see the mysql_select_db() function uses the two variables we defined earlier; $db which is the name of the database we want to select, and $connect which is the connection to the SQL server. The die() function here gives the message “Could not open database:” and the mysql_error() message afterwards if it comes across an error.
Now that we have got our connection settings finished and selected the database we want its now time to start writing the queries. If you don’t have much knowledge of SQL there is a tutorial in the resources section that is worth checking out.
OK to make sure there isn’t already someone in the database with the same username that the user has entered we need to use a SELECT statement which we will assign to the variable $selectstatement. For example:
$selectstatement = “SELECT * FROM yourtable WHERE username=’$username’”;
Where yourtable is replace it with the name of the table you store your user information in.
The next query we will need will be to insert the data into the database. For this we will be using the INSERT statement.
$insertstatement = “INSERT INTO users ( username, password, email, ip ) VALUES ( '$username', '$password', '$email', '$ip' )";
Now that we have our queries wrote and assigned to variables we will use the mysql_num_rows() function to see if anyone has the same username as the one the user specified in our form. We will use the SELECT statement we wrote earlier and pass it through the mysql_num_rows() function. The mysql_num_rows() function takes the result of a query and returns how many rows were returned. For example:
$selectresult = mysql_query( $selectstatement, $connect );
$numrows = mysql_num_rows( $result );
if ( $numrows > 0 ) {
print " The username you have chosen is in use. Please choose another one.";
}
By using the mysql_num_rows() we check to see if more that 0 records have been returned because if they have it means that someone in the database already has the username that they have chosen.
Now to finish off the code for register2.php we just have to add an else clause to the if statement above so it will look like this:
if ( $numrows > 0 ) {
print "The username you have chosen is in use. Please choose another one.";
} else {
mysql_query( $insertstatement, $connect )
or die( "Couldn't add data to table" );
print "Registration successful! Login <a href=\"login.php\">here</a>.";
}
?>
This just means that if all goes well and it passes through all the error checks that it passes the INSERT statement we wrote above through the mysql_query() function and prints the text “Registration successful!” and adds a link to the homepage to the webpage.
So now we have register2.php finished it’s time to move onto the login script.
*** LOGIN.PHP ***
For login.php we will only be using an HTML form no PHP so it should look like this:
<form method="POST" action="login2.php">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit" value="Login">
</form>
Once you have got the form on the login.php page like above it’s time to get onto the code in login2.php.
*** LOGIN2.PHP ***
Before we get into coding login2.php I’m first going to talk about session variables. In order for the website to know if the user is logged on and to remember they are after they have logged on we must start a session. A session gives the user a unique identifier which can be used to store information linked to that ID. For this to work on every page of your website you must start a session before any of the HTML or PHP. Also check the resources for a link about session variables. This code must be displayed at the top of your code on all of your pages:
<?php
session_start();
?>
Later on in the code I will talk more about the session variables and how we will use them but it is important to remember that that piece of code above must be before everything else in the code because if it is not it will not work.
Ok let’s start. Firstly we need to put the POST variables into easier to remember and shorter variable names like is register2.php. So the code will start like this:
<?php
$username = $_POST[‘username’];
$password = $_POST[‘password’];
Next since the password is stored in the database as an MD5 hash we need to use the md5() function that is built into PHP to hash the password. For example:
$password = md5($password);
Now we need to check to make sure that the user has entered data into both the username and password fields. This is done like below:
if ( (!$username) || (!$password) ) {
die(“You did not enter all of the needed information”);
}
This uses the ! operator that we have used previously to check if the $username and $password variables are empty and then if they are performs a die() function which stops running the code and displays an error message. The || operator we use here means OR. Check out the link in the resources section to read up more on the operators used in PHP as they are important.
Now that we’ve done that we need to add our code to connect to the MySQL database like we did in register2.php. Since I’ve more or less explained it already I’ll just add the code below:
[code]
$sqluser = “Test”;
$password = “Test”;
$db = “MyUsers”;
$connect = mysql_connect( "freesql.org", $sqluser, $sqlpass );
if ( ! $connect ) {
die( "Could not connect to SQL server" );
}
mysql_select_db( $db, $connect )
or die ("Could not open database:" .mysql_error() );
OK so now we have everything we need to connect to the database we need to write our query:
$selectstatement = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
To see if the user has entered the right password we need to use the mysql_num_rows() function. This is because the SELECT statement above will return more than 0 rows if the user has entered the correct information so we will use an if statement to finish off the code for login2.php as shown below:
$numrows = mysql_num_rows( $selectstatement );
if ( $numrows > 0 ) {
print “Login successful!”;
$_SESSION[‘username’] = $username;
$_SESSION[‘logged_in’] = “yes”;
} else {
print “Wrong username or password!”;
}
?>
As you can see if the user logs in successfully they get the message “Login successful!” and two session variables are defined. As long as the session_start() function I talked about previously is at the top of all your pages they will be remembered so you can use them on different pages.
You can use these session variables to see if a user is logged on. For example if there was a page on your website that you must be logged in to view you could use some code like this:
if ( $_SESSION[‘logged_in’] = “” ) {
print “You are not authorised to view this page”;
} else {
*** your code here ***
}
This code checks to see if the $_SESSION[‘logged_in’] variable is empty and if it is it displays an error message.
A use of the $_SESSION[‘username’] variable could be to display the users name on the website. For example:
if ( $_SESSION[‘username’] = “” ) {
print “You are not logged in!”;
} else {
print “Welcome $_SESSION[‘username’]!”;
}
Ok that’s it for login2.php and the user system is nearly ready, all we need to do now is write a script so the user can log out.
*** LOGOUT.PHP ***
This is only a few lines of code so here it is and I’ll explain after:
<?php
if ( $_SESSION['logged_in'] = “” ) {
echo "You are already logged out!";
} else {
session_destroy();
echo "You are now logged out.";
}
?>
Here we use the session variables we defined earlier again. The if statement checks that if the variable $_SESSION[‘logged_in’] is empty that it tells the user that they are already logged out. If not it uses the session_destroy() function that destroys the session and gives the user the message “You are now logged out”.
Ok so that’s the user system finished and if your ready it I hope it has been a help. If there any questions or problems with it just leave a comment and I’ll try to get an answer back to you.
-Rikeku
*** RESOURCES ***
PHP Operators: http://www.w3schools.com/php/php_operators.asp
Basic SQL: http://www.baycongroup.com/basic_sql_commands.htm
PHP Sessions: http://www.htmlgoodies.com/beyond/php/article.php/3472581
***