In this tutorial, I walk you through the complete process of creating a user registration system where users can create an account by providing username, email and password, login and logout using PHP and MySQL. I will also show you how you can make some pages accessible only to logged in users. Any other user not logged in will not be able to access the page.
If you prefer a video, you can watch it on my YouTube channel
The first thing we"ll need to do is set up our database.
Create a database called registration . In the registration database, add a table called users . The users table will take the following four fields.
- username - varchar(100)
- email - varchar(100)
- password - varchar(100)
You can create this using a MySQL client like PHPMyAdmin.
Or you can create it on the MySQL prompt using the following SQL script:
CREATE TABLE `users` (`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `username` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(100) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And that"s it with the database.
Now create a folder called registration in a directory accessible to our server. i.e create the folder inside htdocs (if you are using XAMPP server) or inside www (if you are using wampp server).
Inside the folder registration, create the following files:
Open these files up in a text editor of your choice. Mine is Sublime Text 3.
Registering a user
Open the register.php file and paste the following code in it:
regiser.php:
Register
Nothing complicated so far right?
A few things to note here:
First is that our form"s action attribute is set to register.php. This means that when the form submit button is clicked, all the data in the form will be submitted to the same page (register.php). The part of the code that receives this form data is written in the server.php file and that"s why we are including it at the very top of the register.php file.
Notice also that we are including the errors.php file to display form errors. We will come to that soon.
As you can see in the head section, we are linking to a style.css file. Open up the style.css file and paste the following CSS in it:
* { margin: 0px; padding: 0px; } body { font-size: 120%; background: #F8F8FF; } .header { width: 30%; margin: 50px auto 0px; color: white; background: #5F9EA0; text-align: center; border: 1px solid #B0C4DE; border-bottom: none; border-radius: 10px 10px 0px 0px; padding: 20px; } form, .content { width: 30%; margin: 0px auto; padding: 20px; border: 1px solid #B0C4DE; background: white; border-radius: 0px 0px 10px 10px; } .input-group { margin: 10px 0px 10px 0px; } .input-group label { display: block; text-align: left; margin: 3px; } .input-group input { height: 30px; width: 93%; padding: 5px 10px; font-size: 16px; border-radius: 5px; border: 1px solid gray; } .btn { padding: 10px; font-size: 15px; color: white; background: #5F9EA0; border: none; border-radius: 5px; } .error { width: 92%; margin: 0px auto; padding: 10px; border: 1px solid #a94442; color: #a94442; background: #f2dede; border-radius: 5px; text-align: left; } .success { color: #3c763d; background: #dff0d8; border: 1px solid #3c763d; margin-bottom: 20px; }
Now the form looks beautiful.
Let"s now write the code that will receive information submitted from the form and store (register) the information in the database. As promised earlier, we do this in the server.php file.
Open server.php and paste this code in it:
server.php
Sessions are used to track logged in users and so we include a session_start() at the top of the file.
The comments in the code pretty much explain everything, but I"ll highlight a few things here.
The if statement determines if the reg_user button on the registration form is clicked. Remember, in our form, the submit button has a name attribute set to reg_user and that is what we are referencing in the if statement.
All the data is received from the form and checked to make sure that the user correctly filled the form. Passwords are also compared to make sure they match.
If no errors were encountered, the user is registered in the users table in the database with a hashed password. The hashed password is for security reasons. It ensures that even if a hacker manages to gain access to your database, they would not be able to read your password.
But error messages are not displaying now because our errors.php file is still empty. To display the errors, paste this code in the errors.php file.
0) : ?>
When a user is registered in the database, they are immediately logged in and redirected to the index.php page.
And that"s it for registration. Let"s look at user login.
Login user
Logging a user in is an even easier thing to do. Just open the login page and put this code inside it:
Login
Everything on this page is quite similar to the register.php page.
Now the code that logs the user in is to be written in the same server.php file. So open the server.php file and add this code at the end of the file:
// ... // LOGIN USER if (isset($_POST["login_user"])) { $username = mysqli_real_escape_string($db, $_POST["username"]); $password = mysqli_real_escape_string($db, $_POST["password"]); if (empty($username)) { array_push($errors, "Username is required"); } if (empty($password)) { array_push($errors, "Password is required"); } if (count($errors) == 0) { $password = md5($password); $query = "SELECT * FROM users WHERE username="$username" AND password="$password""; $results = mysqli_query($db, $query); if (mysqli_num_rows($results) == 1) { $_SESSION["username"] = $username; $_SESSION["success"] = "You are now logged in"; header("location: index.php"); }else { array_push($errors, "Wrong username/password combination"); } } } ?>Again all this does is check if the user has filled the form correctly, verifies that their credentials match a record from the database and logs them in if it does. After logging in, the user is redirected them to the index.php file with a success message.
Now let"s see what happens in the index.php file. Open it up and paste the following code in it:
Home Page
Welcome
logout
The first if statement checks if the user is already logged in. If they are not logged in, they will be redirected to the login page. Hence this page is accessible to only logged in users. If you"d like to make any page accessible only to logged in users, all you have to do is place this if statement at the top of the file.
The second if statement checks if the user has clicked the logout button. If yes, the system logs them out and redirects them back to the login page.
Now go on, customize it to suit your needs and build an awesome site. If you have any worries or anything you need to clarify, leave it in the comments below and help will come.
You can always support by sharing on social media or recommending my blog to your friends and colleagues.
A tutorial for the very beginner! No matter where you go on the Internet, there"s a staple that you find almost everywhere - user registration. Whether you need your users to register for security or just for an added feature, there is no reason not to do it with this simple tutorial. In this tutorial we will go over the basics of user management, ending up with a simple Member Area that you can implement on your own website.
If you need any extra help or want a shortcut, check out the range of PHP service providers on Envato Studio. These experienced developers can help you with anything from a quick bug fix to developing a whole app from scratch. So just browse the providers, read the reviews and ratings, and pick the right one for you.
Introduction
In this tutorial we are going to go through each step of making a user management system, along with an inter-user private messaging system. We are going to do this using PHP, with a MySQL database for storing all of the user information. This tutorial is aimed at absolute beginners to PHP, so no prior knowledge at all is required - in fact, you may get a little bored if you are an experienced PHP user!
This tutorial is intended as a basic introduction to Sessions, and to using Databases in PHP. Although the end result of this tutorial may not immediately seem useful to you, the skills that you gain from this tutorial will allow you to go on to produce a membership system of your own; suiting your own needs.
Before you begin this tutorial, make sure you have on hand the following information:
- Database Hostname - this is the server that your database is hosted on, in most situations this will simply be "localhost".
- Database Name, Database Username, Database Password - before starting this tutorial you should create a MySQL database if you have the ability, or have on hand the information for connecting to an existing database. This information is needed throughout the tutorial.
If you don"t have this information then your hosting provider should be able to provide this to you.
Now that we"ve got the formalities out of the way, let"s get started on the tutorial!
Step 1 - Initial Configuration
Setting up the database
As stated in the Introduction, you need a database to continue past this point in the tutorial. To begin with we are going to make a table in this database to store our user information.
The table that we need will store our user information; for our purposes we will use a simple table, but it would be easy to store more information in extra columns if that is what you need. In our system we need the following four columns:
- UserID (Primary Key)
- Username
- Password
- EmailAddress
In database terms, a Primary Key is the field which uniquely identifies the row. In this case, UserID will be our Primary Key. As we want this to increment each time a user registers, we will use the special MySQL option - auto_increment .
The SQL query to create our table is included below, and will usually be run in the "SQL" tab of phpMyAdmin.
CREATE TABLE `users` (`UserID` INT(25) NOT NULL AUTO_INCREMENT PRIMARY KEY , `Username` VARCHAR(65) NOT NULL , `Password` VARCHAR(32) NOT NULL , `EmailAddress` VARCHAR(255) NOT NULL);
Creating a Base File
In order to simplify the creation of our project, we are going to make a base file that we can include in each of the files we create. This file will contain the database connection information, along with certain configuration variables that will help us out along the way.
Start by creating a new file: base.php , and enter in it the following code:
Let"s take a look at a few of those lines shall we? There"s a few functions here that we"ve used and not yet explained, so let"s have a look through them quickly and make sense of them -- if you already understand the basics of PHP, you may want to skip past this explanation.
Session_start();
This function starts a session for the new user, and later on in this tutorial we will store information in this session to allow us to recognize users who have already logged in. If a session has already been created, this function will recognize that and carry that session over to the next page.
Mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error()); mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
Each of these functions performs a separate, but linked task. The mysql_connect function connects our script to the database server using the information we gave it above, and the mysql_select_db function then chooses which database to use with the script. If either of the functions fails to complete, the die function will automatically step in and stop the script from processing - leaving any users with the message that there was a MySQL Error.
Step 2 - Back to the Frontend
What Do We Need to Do First?
The most important item on our page is the first line of PHP; this line will include the file that we created above (base.php), and will essentially allow us to access anything from that file in our current file. We will do this with the following line of of PHP code. Create a file named index.php , and place this code at the top.
Begin the HTML Page
The first thing that we are going to do for our frontend is to create a page where users can enter their details to login, or if they are already logged in a page where they can choose what they then wish to do. In this tutorial I am presuming that users have basic knowledge of how HTML/CSS works, and therefore am not going to explain this code in detail; at the moment these elements will be un-styled, but we will be able to change this later when we create our CSS stylesheet.
Using the file that we have just created (index.php), enter the following HTML code below the line of PHP that we have already created.
What Shall We Show Them?
Before we output the rest of the page we have a few questions to ask ourselves:
- Is the user already logged in?
- Yes - we need to show them a page with options for them to choose.
- No
- Yes - we need to check their details, and if correct we will log them into the site.
- No - we continue onto the next question.
These questions are in fact, the same questions that we are going to implement into our PHP code. We are going to do this in the form of if statements . Without entering anything into any of your new files, lets take a look at the logic that we are going to use first.
Looks confusing, doesn"t it? Let"s split it down into smaller sections and go over them one at a time.
If(!empty($_SESSION["LoggedIn"]) && !empty($_SESSION["Username"])) { // let the user access the main page }
When a user logs into our website, we are going to store their information in a session - at any point after this we can access that information in a special global PHP array - $_SESSION . We are using the empty function to check if the variable is empty, with the operator ! in front of it. Therefore we are saying:
If the variable $_SESSION["LoggedIn"] is not empty and $_SESSION["Username"] is not empty, execute this piece of code.
The next line works in the same fashion, only this time using the $_POST global array. This array contains any data that was sent from the login form that we will create later in this tutorial. The final line will only execute if neither of the previous statements are met; in this case we will display to the user a login form.
So, now that we understand the logic, let"s get some content in between those sections. In your index.php file, enter the following below what you already have.
Member Area
=$_SESSION["EmailAddress"]?>
.
Success";
echo "We are now redirecting you to the member area.
"; echo ""; } else { echo "Error
"; echo "Sorry, your account could not be found. Please click here to try again.
"; } } else { ?>Member Login
Thanks for visiting! Please either login below, or click here to register.
Hopefully, the first and last code blocks won"t confuse you too much. What we really need to get stuck into now is what you"ve all come to this tutorial for - the PHP code. We"re now going to through the second section one line at a time, and I"ll explain what each bit of code here is intended for.
$username = mysql_real_escape_string($_POST["username"]); $password = md5(mysql_real_escape_string($_POST["password"]));
There are two functions that need explaining for this. Firstly, mysql_real_escape_string - a very useful function to clean database input. It isn"t a failsafe measure, but this will keep out the majority of the malicious hackers out there by stripping unwanted parts of whatever has been put into our login form. Secondly, md5 . It would be impossible to go into detail here, but this function simply encrypts whatever is passed to it - in this case the user"s password - to prevent prying eyes from reading it.
$checklogin = mysql_query("SELECT * FROM users WHERE Username = "".$username."" AND Password = "".$password."""); if(mysql_num_rows($checklogin) == 1) { $row = mysql_fetch_array($checklogin); $email = $row["EmailAddress"]; $_SESSION["Username"] = $username; $_SESSION["EmailAddress"] = $email; $_SESSION["LoggedIn"] = 1;
Here we have the core of our login code; firstly, we run a query on our database. In this query we are searching for everything relating to a member, whose username and password match the values of our $username and $password that the user has provided. On the next line we have an if statement, in which we are checking how many results we have received - if there aren"t any results, this section won"t be processed. But if there is a result, we know that the user does exist, and so we are going to log them in.
The next two lines are to obtain the user"s email address. We already have this information from the query that we have already run, so we can easily access this information. First, we get an array of the data that has been retrieved from the database - in this case we are using the PHP function mysql_fetch_array . I have then assigned the value of the EmailAddress field to a variable for us to use later.
Now we set the session. We are storing the user"s username and email address in the session, along with a special value for us to know that they have been logged in using this form. After this is all said and done, they will then be redirect to the Member Area using the META REFRESH in the code.
So, what does our project currently look like to a user?
Great! It"s time to move on now, to making sure that people can actually get into your site.
Let the People Signup
It"s all well and good having a login form on your site, but now we need to let user"s be able to use it - we need to make a login form. Make a file called register.php and put the following code into it.
Sorry, that username is taken. Please go back and try again.
"; } else { $registerquery = mysql_query("INSERT INTO users (Username, Password, EmailAddress) VALUES("".$username."", "".$password."", "".$email."")"); if($registerquery) { echo "Success
"; echo "Your account was successfully created. Please click here to login.
"; } else { echo "Error
"; echo "Sorry, your registration failed. Please go back and try again.
"; } } } else { ?>Register
Please enter your details below to register.