Simple User Registration & Login Script in PHP and MySQLi

Today i will share Simple User Registration & Login Script in PHP and MySQLi, i will explain the basic functionality of registration and access secured area. In this tutorial user can register, login to member secured area and logout.

I am using PHP 5.6 for this tutorial, i didn’t check this tutorial on PHP 7, kindly make sure you are using PHP 5.6 to avoid any unexpected error.

Create a Database Table with Following Five Fields:
id, username, email, password, trn_date

Create a Registration Form

Create a Login Form

Connect to the Database by using PHP

Authenticate Logged in User

Create Index Page

Create Dashboard Page

Create a Log Out

Create a CSS File

1. Create a Database

To create a database, login to phpmyadmin and click on database tab, enter your database name and click on create database button or simply execute the below query. In my case i created database with the name register.

1

CREATEDATABASEregister;

2. Creating a Database Table

To create table, execute the below query in SQL.

1

2

3

4

5

6

7

8

CREATETABLEIF NOT EXISTS`users`(

`id`int(11)NOT NULLAUTO_INCREMENT,

`username`varchar(50)NOT NULL,

`email`varchar(50)NOT NULL,

`password`varchar(50)NOT NULL,

`trn_date`datetimeNOT NULL,

PRIMARY KEY(`id`)

);

3. Creating a Registration Form

Simple create a page with name registration.php and paste the following code in it.

Warning: session_start(): Cannot send session cookie – headers already sent by (output started at /storage/ssd2/379/3566379/public_html/display/auth.php:7) in /storage/ssd2/379/3566379/public_html/display/auth.php on line 9

Warning: session_start(): Cannot send session cache limiter – headers already sent (output started at /storage/ssd2/379/3566379/public_html/display/auth.php:7) in /storage/ssd2/379/3566379/public_html/display/auth.php on line 9

Warning: Cannot modify header information – headers already sent by (output started at /storage/ssd2/379/3566379/public_html/display/auth.php:7) in /storage/ssd2/379/3566379/public_html/display/auth.php on line 11

Hi!,I really like your writing so a lot! share we communicate more approximately your article on AOL? I need a specialist on this area to unravel my problem. Maybe that is you! Taking a look forward to peer you.

Well there is nothing additional script which may arise when using different browser, i wounder i never saw something like this before in my code. I will be better if you can share any live URL if you have so that we can have a look on it.

Hi, maybe a stupid question, but is simply setting $_SESSION[‘username’] secure? What if a malicious person would brute-force try setting $_SESSION with random usernames, and it finds a real username, it could just login bypassing password check?

HI Laurens, there are many security measures that you should take, purpose of this tutorial is to keep it simple so that everyone can understand how it works, this is not for production use, you will need to do more security checks to implement any user registration system.

Hi, great work everything works, but I would like to add an image. In my db I have the path to it (i’m working on localhost). But when i try to display it on my webpage, the broken image appears.
If you could help me a bit

Hi Andrej, thanks for liking my tutorial.
Kindly check these things
1. Make sure your image file exist in your image file location
2. Check your image file extension is correct.
3. Also check url of image in your source code, copy and paste the image url in new tab to view is image viewing in new tab or not. If image is not working in new tab then you must check is file really exist in that directory.
Hope this help you.

Well as you can see i am checking it on same page, so it is not possible to open this message on new window, however there may be some virus at your system which is opening new tab. I suggest you to register with simple user and password, also make sure that your registration data is in database.

Thank you so much sir for the demo code…..its perfect.
I am having a challenge with phpmailer, i edited the code that before registration details are stored unto my db, i need to verify the user email…plz help

include(“auth.php”); is created to check and redirect if user is not logged in.
I have placed this file at the top of index.php.
It is working fine, but if you are still getting issue, i would recommend to check it on PHP 5.4. If this is version issue.

session_start() must be at the top of your source, no html or other output before!
you can only send session_start() one time
better to do it this way if(session_status()!=PHP_SESSION_ACTIVE) session_start()

I’m really enjoying the theme/design of your web
site. Do you ever run into any browser compativility issues?
A couple of my blog readers have complained bout my wevsite not operating correctly in Explorer but looks great in Chrome.
Do you have any recommendations to help fix this problem?

I did everything according to tutoria, however, when I put correct “login” and”password”, which ive put into database, the “Username/password is incorrect.” pops in. I cannot find where’s there’s a problem

well unfortunately for such a clear tutorial , all the visitors comments that are facing the same issue such as i am where the login.php page only loads into blank where the connection is properly connected and username and password are correct are just being ignored.
I wish a clear answer can be provided for all of us that are not able to use this tutorial and will move on to the next google search on how to set this up

As you can see it is connection error, kindly make sure that your connection is established, $con variable is defined in db.php. Please enter your database credentials here to get connected with database, such as username, password, host. Check db.php file.

You can do this, all you need to do is check another check which you will create. for example create another column with name admin and INSERT 0 in that column if member is registering and 1 if Admin, normally we do not create admin through portal, we directly add admin from MySQL and enable registration option for members only.
So to view file just check if user admin value is 0 or 1. If 1 then show files.

Thanks for your tutorial. You code works fine. Keep up the good works. I added some other field to the form. I added First Name, Last Name and age. I want to fetch the whole of the data from the database from each row. This mean each data will be fetch from each column in a row. I want the result to display on index.php please what is the code i will add for this function and which page will i place the code? Thank you, God bless

Adding password without encryption is not good practice, this also include the privacy of user, but if you just want to see the same password in db only for testing purpose, you can just remove md5() function from code.

it is not working in my additional pages.
it is working in only my home page.
for example when i opened localhost/saghar then it worked correct but when i opend localhost/saghar/contact.php it does not worked. i gave it 4/5 stars because i knew solution for it.

I’ve solved the issue everyone is having (after login). Here is how you fix it in 2 simple steps.

Take the Login.php code and move the HTML part in the top down to below the php code. (Note: PHP code must be in the top in order for the redirect to work). Also, add your URL into the redirect URL line: (see below).

This is brilliant. For a beginner to understand this it is purely simple and easy to understand code.
I have used everything as shown, just changed to suit my database and parameters.
The registration works perfect.

I had some problems with the login page however.
First, due to the md5 for password somehow it was reading the key stored in the database. I changed that and that is solved.
The second issue which i am unable to solve which is actually a repeat by some other comments above, is the redirect after login to the index page where it would show the username based on the session.

Thanks for perfectly simple example, it’s exactly what I needed. Almost 🙂
Though, I want to use it only as an addition to another website, yet it insists to make user log in before they can enter main index file.
Is there a simple way to change this?

Thank you for your good work.
But after registration and login, I only get a blank page.
If I open index page when I log in, I’ll think so
BUT, you want to get to index.php directly when you log in.
This does not help
Session_start ();
Require (‘db.php’);

Hi Javed. First of all thanks for the whole tutorial…but after i successful login, it just refresh the login.php but with a totally blank…is it any php tutorial for the connection after login? and after the registration…the data that i key in was not exist in the database…

thank you i have neen using this for some time both versions . recently the <5.5 version has curiously stopped working. i cannot discover if it is a php upgrade or not as my hosting has changed. version now is 5.4.45. shame i love the simplicity of this script

“Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at C:\xampp\htdocs\xampp\seva1\login.php:9) in C:\xampp\htdocs\xampp\seva1\login.php on line 10

I tried to run this on my apache server and when I navigated to the registration page all I got was a blank page. Do you know where I need to save the css file or can I just change the code to include the filepath? Also do I keep or remove all the quotations in the code?

inside the db.php file —-$con = mysqli_connect(“localhost”,”root”,””,”register”); inplace of root you should write your database name and insside “” it is for password and inplace of register you need to place your table name

I’m no expert with PHP, but I do know that md5 is totally unsafe. Shouldn’t be used for anything you care about. Aren’t there better built in PHP functions for encrypting passwords? Also, what about prepared statements SQL queries?

I like your system. Can I add to the registration form a field that accepts a registration number (sent to the user in advance) that validates the number from a database list and then, if valid, continues with the rest of the registration process?
If so, can the login part of the script then give access to the private folder, or does yet another script have to exist on every html page within the private folder for each page to be accessible?

Well tom, i actually didn’t get you clearly, but if you want to give registration unique no. or id then you can simply fetch the user id and give it to user, and giving access to private folder can be possible but it will be more advance feature, and currently i didn’t write any tutorial about it.

Hi Javed, nice prog. Works OK on my Linux setup. I would suggest in order to increase password security (at least for those who use passwords in Xampp or other database setup and including phpmyadmin, to put the db.php file outside the webroot. In other words put the file in the user root in a directory called ext_include and call that in the login and registration php files as follows ‘require’/ext_include/db.php’; This means that web users cannot readily discover the phpmyadmin (database0 password.
I have altered it for my own set-up. I will when ready with other small modifications let you know to benefit all.#Well done on this, it saved me a few days headaches and paracetamols. Thanks

Yes you are right, but what i tried here, i simple explain how things work, obviously there is much things for improvement but that should be deal in the later stage, my focus was only to tell the newbie how it actually works 🙂 thanks for your input.

when I do the copy paste of what u have instructed it works but I can’t login using the same codes in my other db, but I can register, and when I try to login after registration it shows incorrect username/password even though my username and password are correct….by the way I’ve changed db name in db.php, table name in login.php and registration.php..where should I correct more…plis help!!! presentation nearby 🙂

Sorry for the late reply, i was busy in some other tasks, well i think there may be some issue related to DB connection, you should try to connect db first, if you are changing it, and make sure if you register then its data is in database.

Hi Mr. Javad the code is not complete please I want you to send the code the complete codes of all the attributes in a PDF format into my email please thanks… daniel@**** and may I ask a question…
Do you know how to design/program a website confirmation like mmm or any ponzi scheme that when any one registers it send activation to some other user?

Goodevening Javed, thanks for the script. I am creating a volunteer website. Assuming I have 10 volunteers who have registered for the program (user-id 1-10), how can I echo the details of user-id 5 (name, phone number and department) to show on the dashboard of user-id 3 and vice-versa. Thanks.

Very good tutorial!
But I have problem:
“Warning: session_start(): Cannot send session cookie – headers already sent by (output started at /auth.php:8) in /auth.php on line 9”
Each file is saved without BOM (UTF-8 BOM). Only UTF-8. What can I do?

Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at C:\xampp\htdocs\simple-user-registration-login\auth.php:8) in C:\xampp\htdocs\simple-user-registration-login\auth.php on line 9

Warning: Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\simple-user-registration-login\auth.php:8) in C:\xampp\htdocs\simple-user-registration-login\auth.php on line 11

I like your code and it seems it will work well. I am having an issue on all pages like registration and login, where when i fill in the information and click on the button, it just reloads the page. No error, no successful message and the database is not updated. I can use INSERT INTO and it will insert into the database so I know it is connected, but it will not do it when i use the register button

Thanks Samuel,
Well yes you can create expire date field and enter value in it using date() function, you can enter any date you want, just Google it and you will have lots of date formats along with future dates.
and for registration code i actually didn’t get you clearly but if you are saying that user will provide registration code which is provide to them manually, then you can simply compare any field using any value either in database or in PHP page if registration code is similar. Otherwise you will need to create another table in DB add all the Reg. Code there and find the user provided code in the table first, if it matches then proceed to register.

Hi Javed,
When I try to register it gives me this error msg: “Failed to connect to MySQL: Access denied for user ‘root’@’localhost’ (using password: NO)”
,so what can I do to fix that??
Thanks in advance

the username on the if line, whenever i change it the script would stop working/not redirect to any page and i would like to know how does it work or if it does grab something from the db.php, thank you

Everything works wonderfully on my site, however, I am having one issue where after login the login.php does not redirect to index.php. So after a successful login, the page refreshes login.php and it is blank. If I manually go to the index.php the session is open and the users info will display correctly. Can you help with the redirect on login to index?

Hello javed
Thank you for sharing this post.
It worked fine till registration and login but once i registered my self and use the login and password which i have created using registration page it doesn’t redirect to index page but gives this error

Cannot modify header information – headers already sent by (****/****/public_html/myaccount/register/login.php:11) in /****/****/public_html/myaccount/register/login.php on line 28

I am getting the same message when I try to login.
………….. Code is Skipped
This is the message that i keep getting after logging in:
Warning: Cannot modify header information – headers already sent by (output started at /home/soiree/public_html/Login/login.php:43) in /home/soiree/public_html/Login/login.php on line 60

Hi Shamanth thanks that you find it helpful, if you are talking about demo link then i have place there demo user and password, you can login only with that one, or if you have set it up on your local server then you should check after registration that is your registration is going into database? If not then you should enable your local phpmyadmin. Or you can try it online if you have any hosting available.

This is exactly what I needed for my existing website. I’m smart enough to figure how to add more required fields and insert the info to my db. However, is there an easy way for me to display a username on a page? As in “Hi [username], welcome to my site”.

Dear Mark, i am glad that you like it, but for payment system there are various options it depends that which option you want to use, like PayPal, or any other payment method. Script for payment will be vary according to your and payment service provider needs.

It seems like after clicking on register button you are getting error, although you can see in my code that if form is submitted it must show either error or successful message, if you can explain it in more detail so may i can i figure out what is actually issue you are facing, are you doing it local server or on host? try it host if you are facing issue in local server, may be problem in your local server or not configured properly.

Hello Javed. Your tutorial and code is awesome. pls can you help implement the query that checks during sign up if a user already exists in the database table; and if it does, the form should display an error message. Thank you so much.

Dear Isah, can you please tell me what kind of problem you are facing? it does not matter what IDE you use, we use IDE to just write and edit our code, if you do not have idea how to run php files on localhost then you can check my tutorial about it. http://www.allphptricks.com/how-to-run-php-files-on-localhost/

You need to make sure that you are providing the correct detail for connecting database, commonly root is the user and make sure you are providing the correct password, if there is no password in your phpmyadmin so you do not need to provide password on local environment.

Thanks for stopping by, Naveed yes you are right but i didn’t use here to check is user already exist or not, i tried to explain simple registration for newbie users. Yes we can implement so many things in registration form. 🙂