Howto: Create a login form in PHP
Howto, php February 7th, 2008On most websites you can register and login as a user. Today, we’re going to create a form where you can register and a form to login. We will use the programming language PHP for it.
Requirements
- Basic knowledge of HTML
- Basic knowledge of PHP
- A webserver and PHP + MySQL
Contents
- Setting up the database
- Creating the database connection
- Creating the registerform
- Handle the registerform
- Creating the loginform
- Handle the loginform
Setting up the database
Create a database for this tutorial. It doesn’t matter what name you use for the database. If you do not know how to create a new database, use the following code.
CREATE DATABASE `login`
When you’re done creating a new database, you’ll need to create the tables. In the tables the data proccessed from the registerform is stored. And the data in the table is used to check if a user has registered.
CREATE TABLE `users` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `username` VARCHAR( 255 ) NOT NULL , `password` VARCHAR( 255 ) NOT NULL , `email` VARCHAR( 255 ) NOT NULL )
In this code, the table users is created. The id is a mandotory value and is used as a primary key. Username, password and email are the fields you want to store data in. They’re given a allowance of 255 characters in a single field. Last, each time new data is stored, the id auto increments, which means the id will increment with ‘one’.
Creating the database connection
Creating the database connection is simple. Enter the following code, but with your own username and password.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php // Your host, 99% of the time it's localhost. $db_host = 'localhost'; // Your username for MySQL. $db_user = 'user'; // Your password for MySQL. $db_pass = 'pass'; // And your given name for the database. $db_name = 'login'; // The database connection. $con = mysql_connect($db_host, $db_user, $db_pass); if(!$con) { die("Cannot connect. " . mysql_error()); } // The database name selection. $dbselect = mysql_select_db($db_name); if(!$dbselect) { die("Cannot select database " . mysql_error()); } ?> |
Just save this file as ‘connection.php’. We’ll include this file in the authenticate page.
Creating the registerform
Create an empty PHP page with the name ‘register.php’ and write the following code within the <body> tags.
<form method="post" action="authenticate.php"> <!-- you can use another action if you'd like --> <label for="username">Username: </label><br /> <input type="text" name="username" id="username"><br /> <label for="password">Password: </label><br /> <input type="password" name="password" id="password"><br /> <label for="password2">Confirm: </label><br /> <input type="password" name="password2" id="password2"><br> <label for="email">Email address:</label><br /> <input type="text" name="email" id="email"><br /> <input type="submit" name="submit" id="submit" value="Submit"> </form>
Handle the registerform
Now it gets interesting. Create another empty PHP page and name it after the action given in the <form action=”"> tag. If you’ve copied the previous code, the page would be named ‘authenticate.php’.
Type in the following code in your PHP page
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | <?php // Include the database connection file. include("connection.php"); // Check if a person has clicked on submit. if(isset($_POST['submit'])) { // Check if a person has filled every form. if(empty($_POST['username']) || empty($_POST['password']) || empty($_POST['password2']) || empty($_POST['email'])) { // Display the error message. echo "You have to fill in everything in the form."; // Exit the code. exit; } // Create variables from each $_POST. $username = $_POST['username']; $password = $_POST['password']; $password2 = $_POST['password2']; $email = $_POST['email']; // Now, compare passwords and check if they're the same. if($password != $password2) { // If the passwords are NOT the same. Again display an error message and redirect. echo "Sorry, wrong password."; exit; } // Secure the password using an md5 hash. $password = md5($password); // Create a variable containing the SQL query. $query = "INSERT INTO `users` (username, password, email) VALUES ('$username', '$password', '$email')"; // Perform the SQL query on the database. $result = mysql_query($query); // If the query failed, display an error. if(!$result) { // The dot seperates PHP code and plain text. echo "Your query failed. " . mysql_error(); } else { // Display a success message! echo "Welcome " . $username . " You are now registered"; } } ?> |
By filling in the registerform. The data from the regsiterform is posted to the PHP file ‘authenticate.php’ and processed. The data is then stored into the database, in the table ‘users’. The user will now be able to log in
Creating the loginform
This is almost the same as creating the registerform.
<form method="post" action="login2.php"> <label for="username">Username: </label><br /> <input type="text" name="username" id="username"><br /> <label for="password">Password: </label><br /> <input type="password" name="password" id="password"><br /> <input type="submit" name="submit" id="submit" value="Submit"> </form>
The user types in his/her username and password and then clicks on submit. In the file ‘login2.php’ we’ll create the login process.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | <?php // login2.php include("connection.php"); // Start a session. Session is explained below. session_start(); // Same checking stuff all over again. if(isset($_POST['submit'])) { if(empty($_POST['username']) || empty($_POST['password'])) { echo "Sorry, you have to fill in all forms"; exit; } // Create the variables again. $username = $_POST['username']; $password = $_POST['password']; // Encrypt the password again with the md5 hash. // This way the password is now the same as the password inside the database. $password = md5($password); // Store the SQL query inside a variable. // ONLY the username you have filled in is retrieved from the database. $query = "SELECT username,password FROM `users` WHERE username='$username'"; $result = mysql_query($query); if(!$result) { // Gives an error if the username given does not exist. // or if something else is wrong. echo "The query failed " . mysql_error(); } else { // Now create an object from the data you've retrieved. $row = mysql_fetch_object($result); // You've now created an object containing the data. // You can call data by using -> after $row. // For example now the password is checked if they're equal. if($row->password != $password) { echo "I am sorry, but the passwords are not equal."; exit; } // By storing data inside the $_SESSION superglobal, // you stay logged in until you close your browser. $_SESSION['username'] = $username; $_SESSION['sid'] = session_id(); // Make it more secure by storing the user's IP address. $_SESSION['ip'] = $_SERVER['REMOTE_ADDR']; // Now give the success message. // $_SESSION['username'] should print out your username. echo "Success! You are now logged in " . $_SESSION['username']; } } |
This all should work fine if you correctly followed everything. I have included a .zip file with the full login form in it. Feel free to comment and ask questions
Download .zip
February 29th, 2008 at 6:35 pm
exactly what i was looking for! did help me a lot! thanks!
just a little typo in ‘register.php’ “You are now registred” …
February 29th, 2008 at 8:48 pm
i had to add “session_start();” to “access.php” .. else it wouldn’t work …
March 1st, 2008 at 12:42 pm
Thanks. Changed the errors.
March 4th, 2008 at 11:33 am
Perfect for my personalized website! big thanks to you bro
March 6th, 2008 at 4:46 pm
Thank’s alot
March 10th, 2008 at 8:23 am
can i change access page layout, colors, images etc.
March 10th, 2008 at 11:49 am
very useful, thanks a lot
March 13th, 2008 at 7:07 pm
What if two users sign up with the same username?
March 17th, 2008 at 6:20 am
if two users signed up with the same username there would be an issue with the row lookup in the select query.
to solve this make the username column in the table unique.
you will probably want to make the email column unique as well.
here’s how to with the example table:
ALTER TABLE users ADD UNIQUE (username,email);
March 17th, 2008 at 9:57 pm
What about validation of submitted Data?
If you use such a login script every trained security-interested programmer can drop your whole database. NEVER EVER submit data which is filled out by user without validating them and replace certain tags!
March 19th, 2008 at 8:57 am
When you assign the $username and $password variable, you can give them a basic security. e.g
$username = mysql_real_escape_string($_POST['username'];
$password = mysql_real_escape_string($_POST['password'];
This is just a howto how to make a real basic login and register form, without adding security checks.
When checking if the desired username already exists try:
$sql = “SELECT username FROM users WHERE username=’$username’”;
if($sql) {
echo “Username already exists”;
} else {
echo “Username doesn’t exist”;
}
March 20th, 2008 at 8:11 pm
I dont know why i am getting this. I have a wamp sever i submited the query to the database in phpmyadmin please tell me how to do this. I just started learning this would love some help thank you. How do i find the user and password for mysql on wampsever(wamp5)
************************************************************
Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘root’@'localhost’ (using password: YES) in D:\wamp\www\PHP\connection.php on line 19
Cannot connect. Access denied for user ‘root’@'localhost’ (using password: YES)
**********************************************************
Then I tried giving blanks in them then I got this
____________________________________________________
Cannot select database Access denied for user ”@’localhost’ to database ‘login’
March 20th, 2008 at 11:01 pm
I tried it on my wampserver it was working i dont know fow to do this in a site. i dont know .Help me please
*************************************************************
Warning: mysql_connect(): Access denied for user ‘rosjos’@'ws5.100ws.com’ (using password: NO) in /home/www/chakaro.100webspace.net/connection.php on line 19
Cannot connect. Access denied for user ‘rosjos’@'ws5.100ws.com’ (using password: NO)
March 22nd, 2008 at 7:24 pm
Awesome, it works! Thanks
Hmm now I need a log out page and a members only page… any ideas on how to do this?
March 24th, 2008 at 8:11 pm
I had to take out the md5() secure function so that I could login after registering. If I left it in the code, then when I tried to login, I got the error stating, “The passwords are not equal.” Meaning that the password I entered was not the same encrypted password in the database. Do you know how to fix this so that I can use the md5() function? Thanks.
April 9th, 2008 at 10:09 pm
I have used some parts of your PHP-code. Thanks for it!
April 10th, 2008 at 8:56 pm
The login works fine, but I am also able to browse directly to the site content page and am not redirected to login.php. Why is this?
I tried to copy the contents of ‘access.php’ and paste it above the html of my content page but to no avail.
What am I missing?
April 21st, 2008 at 5:55 pm
Hi there,
Howto: Create a login form in PHP
I see on the form for the above that in login2.php you ask the user ” For example now the password is checked if they’re equal. if($row->password != $password) ”
The loginform only asks for username and password therefore why would you want to check if passwords are equal, that only applies to initial register.php form where you have to confirm password. Also the download zip file is different for login2.php as it contains a header “Location: login.php” which is not in your script above.
I am trying to learn PHP and all you are doing is confusing me. Please advise
regards
seamus
June 5th, 2008 at 8:17 pm
Hi,
thanks a lot, very usefull script.
For security reasons I would avoid informing user what was wrong with their login atempt - wrong username or wrong password - I would give single response “login failed” in either case.
Also it would be nice using
June 8th, 2008 at 1:58 pm
Great tutorial thanks, but you forgot the “?>” code in the last block =)
June 16th, 2008 at 7:23 pm
Excellent script…works great. Now to further it along. Noting that I am new to all of this!
How can I add a registration confirmation…i.e. e-mail with a link to activate without directly activating by submission. This is an obvious security question.
Then once they are registered, how do I secure pages BEHIND that login to prevent access to the pages. I am reading through more of this so if I happen to find the information I appologise in advance, but maybe someone can help point me in the right direction.
I have a site that is going to have a ‘members’ section that requires this, obviously, and I want to build it myself vs. having someone else do it. I want/need to learn this stuff..:)
thanks!! keep up the great work!
June 27th, 2008 at 9:38 pm
I can’t get login.php to submit. The form clears and login2.php never executes. Do I need the absolute URL in the action=? That didn’t work either. Please respond.
Thanks for the script.
August 12th, 2008 at 4:45 am
That’s awesome, it’s the first login script that i found in the internet and work perfectly. Thanx very much…you’re the best…
I doens’t looking for yet, but the logout script it’s missing, i think…
August 16th, 2008 at 10:55 pm
Thanks for this script.
But I have a problem. I can not log out it. Please give a log out script for this script.
August 20th, 2008 at 9:47 pm
To log out:
session_destroy();
September 3rd, 2008 at 3:10 am
I would like to have people register (new users Register)
(Current users login) I have a flash site that i built but can not figure this out. I live in omaha , Nebraska
Would even like the forgot password option
Thanks
Barry
September 17th, 2008 at 9:06 pm
Thanx men !!!
I spend a few days searching for a script like that, i found it here… Bye from Venezuela !!!
3fr@out !!!
September 19th, 2008 at 10:49 am
how to make that user cannot register with already used username?
September 27th, 2008 at 12:33 pm
hi…
where should i put “session_destroy();” code to log out ???
September 30th, 2008 at 1:38 pm
Amazing Tutorial!!! n the code works perfectly. Only thing I want to know is how to link the pages. Whay I mean is after the registration page the user should be taken to the login page directly ??
Thnks n Regards.
November 11th, 2008 at 6:00 am
Hi There i tried the code but when i try it on my webserver and it works fine accept if i try to register or login i get the message Your query failed. Table ‘login.users’ doesn’t exist
Im very new at this so can someone help me out please what am i doing wrong or and what is md5??.
greetings rinaldo
November 13th, 2008 at 3:04 pm
hi it is realy very good.will you please post the script to reduce the size of an uploading image…….
November 17th, 2008 at 6:12 pm
Hi,
It would be better if you please mail me the method to create a page which should come when the and password comes correct. Please help me in this case guys. I am gonna create a website wanting this whole code processes.
November 18th, 2008 at 5:56 am
Hi, Very good script!!
Really usefull, Thanks!!
But I need a lot of help, I was traying the function to check if the nickname exist, but i can´t u_u, I use …
$sql = “SELECT username FROM `users` WHERE username=’$username’;”;
$resultx = mysql_query($sql);
print mysql_error();
echo($resultx),”";
And after :
$num_rows= mysql_num_rows($resultx);
if ($num_rows)!=0){
echo “Username already exists”;
} else {
echo “Correct”;
}
And the error…
Parse error: syntax error, unexpected T_IS_NOT_EQUAL in ….
And..
Value of resultx is: Resource id #3
Value of $num_rows is: 0
WTF??!!! What is id #3!! All the time the value of $num_rows is 0!! due the value of the query.
Can you help me?
Thanks
November 19th, 2008 at 6:14 pm
Hi yaar,
Great coding. I want to know how to include some data into the page that appears after the login. How to do that? Can i merge a simple HTML file along with that or an ASP.NET File. IF yes please mail me the infos to praveenvarghese02@gmail.com.
Please guys. If i can merge please explain a technique by which the users cant access the page just with the link that appears during login and getting into that page without login so that any one wothout registration can do it.
Thank You!!!
November 20th, 2008 at 7:56 am
you have extremely thanks for serve code for login and registration
December 7th, 2008 at 8:58 pm
Very nicely done! For my purposes, I changed username to id, and added l_name and f_name, witha DB named fto and table named emp. When I try to register, a blank page returns.
Thanks in advance for any help!
Below are the scripts register and authenticate;
id:
Password:
—————
December 28th, 2008 at 3:27 pm
Hi i am using your script and have a problem. I keep getting the following message :
Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘a6814003′@’localhost’ (using password: YES) in /home/a6814003/public_html/connection.php on line 13
Free Web Hosting
Cannot connect. Access denied for user ‘a6814003′@’localhost’ (using password: YES)
January 8th, 2009 at 7:48 pm
Hey Adrian, wow, what a great script, it worked flawlessly. I have a question though: what snippet do I enter into pages I want protected? Thanks!
January 27th, 2009 at 1:01 pm
i am new in php and i am a vb programmer.please can u help me out in php.i want to be a php programmer
January 31st, 2009 at 10:51 am
Hi Adriaanvm,
Your PHP login form does not have a plausible logout form, the session is not initialized, you use the session_start() function which doesn’t initialize properly because you have multiple pages. Then when you go to logout (session_destroy()) it gives you an error and doesn’t let you log out.
Can you please advise?
Thanks
February 2nd, 2009 at 10:35 pm
can you tell me how to create a new database and where? Because when I try to create it in myphpadmin in wampserver, it shows mysql error.
February 5th, 2009 at 3:56 pm
Nice!
February 5th, 2009 at 4:01 pm
hi nice tutorial really helpful!
however how would i limit the access to the pages AFTER login before even logging?
got a bit confused on that
February 8th, 2009 at 8:14 pm
Thx dude.. nice tutorial..
antonis. in all your pages you want restriction include a check before the pages to know whether session has been created during login.. The coding seems basic and its pretty customizable with the tutorial given.. Tuning it for more security :P.. thx a lot for nice tuit.. and also how do i get my logout pages.. i am only an html coder.. session destroy command will be enough??
February 14th, 2009 at 1:13 am
Hey, does anybody know how to create a logout page. Whenever I try to unset or destroy the sessions nothing happens. The sessions don’t go away
Thanks for any help.
February 20th, 2009 at 4:33 am
Thank a lot.
February 20th, 2009 at 5:38 pm
Hi,
I am very new to PHP and i just wanted a login page. Your code helped me. I guess it had all what i required.
Thanks a lot !!!
Keep up the good work.
Cheers!!!
Prabesh
March 31st, 2009 at 5:54 am
Что то мне как то не очень, но что то в этом существует.
March 31st, 2009 at 10:16 am
Хай,ТС!!!
У вас на странице символы как квадратики- решите проблему, ато хочется прочитать
April 1st, 2009 at 2:28 pm
Драсте,блогер!!!
У вас на блоге слова как крякозябры какието- исправьте, ато хочется прочитать
April 2nd, 2009 at 10:38 am
Хай,хозяин сайта!!!
У вас на странице слова как абракадабр- решите проблему, ато хочется прочитать
April 15th, 2009 at 11:15 am
Теперь я скажу несколько слов о подводке к дичи молодой собаки и о ее стойке.(В работе собаки по дичи следует различать 4 момента (подразделения) ее работы:
1 — поиск, длящийся до того момента, как собака начнет причуивать признаки присутствия дичи в доступном для ее чутья расстоянии;
2 — потяжку — работа собаки, разбирающейся в донесшемся до нее запахе до момента окончательного определения ею наличия дичи; эта работа заканчивается
April 15th, 2009 at 3:52 pm
Драсте,админ!!!
Сильно понравилась пост. Почитал посты, то скажу, что творите очень познавательно и выбираете интересные категории информации. Большое Спасибо!!!
April 24th, 2009 at 6:36 am
you said, ‘If you do not know how to create a new database, use the following code.
CREATE DATABASE `login”
is in’t confusing? at least confused me. please make it more clear..
April 25th, 2009 at 8:47 am
oh weh… i thought there’s no registration form in here.. heheheh.. i was happy when i opened the zip file.. thanks for sharing this xD.. more power..
April 25th, 2009 at 9:01 am
wait.. speaking of registration form, do u have any suggestions how to trace somebody who are registered? i mean, when they are registered in the database, the ip, date, user_agent and etc, are track. how im gonna do that? xD
April 26th, 2009 at 7:50 am
Дауж. Чево токо не бывает в этом мире.
April 26th, 2009 at 8:50 am
В прошлом годы был на Ибице, так там познакомился с человеком, у которого стиль изложения материала очень похож на ваш. Но, к сожалению, тот человек очень далек от Интернета.
April 26th, 2009 at 9:46 am
Подойдя к второму обзацу необходимо будет побороть в себе желание его пропустить!
April 26th, 2009 at 11:07 am
И придратся то не к чему вообще. а я так люблю покритиковать чужие мысли)))
April 27th, 2009 at 7:12 am
Как рисовали, подделывали и хоронили советские деньги
April 27th, 2009 at 9:24 pm
Thank you author
April 30th, 2009 at 7:30 am
Is there a way to redirect a user after login to his profile page e.g http://www.mywebsite/profile/user.php How can one also restrict the user from going directly to http://www.mywebsite/profile/user.php without logging in?
May 1st, 2009 at 4:32 pm
Plurked
May 1st, 2009 at 4:57 pm
Nice tutorial. thank you.
May 3rd, 2009 at 11:08 pm
I downloaded and ran the zip file but the output gave “query failed” error.What is the solution?
May 4th, 2009 at 6:09 pm
Да,согласен с предыдущими вы блоггерами
May 5th, 2009 at 4:19 pm
Прикольна придумали вы тут
May 6th, 2009 at 10:49 am
Hi, good post. I have been thinking about this topic,so thanks for sharing. I’ll probably be subscribing to your posts. Keep up great writing
May 6th, 2009 at 10:57 pm
Great form…but it gave me an error when i entered wrong username and password, that the $row object is not an object
so one way to solve it is to fetch the number of rows before fetching the $row object
$num_rows = mysql_num_rows($result);
if ($num_rows != 0){ …
May 10th, 2009 at 6:19 pm
I downloaded and ran the zip file but the output gave “query failed” error.What is the solution? Please kindly reply.
May 16th, 2009 at 10:26 am
До глубины души согласен с 1ым ответом. Это того стоит…
May 16th, 2009 at 6:04 pm
ЧТО Ж ДЕЛАТЬ?
May 17th, 2009 at 5:40 pm
мега зачот!
May 18th, 2009 at 7:09 pm
Даже не стану каментировать. просто промолчу
May 19th, 2009 at 12:08 pm
Any chance i can use this with a Microsoft SQL database
May 19th, 2009 at 12:12 pm
Мысль замечательная. Результатами произведенных экспериментов может кто-то поделиться?
May 20th, 2009 at 4:29 pm
The integrated PDF Reader Kindle on the DX is also another welcome feature, since many documents in these days there are in PDF format, so it is a breeze to tote around wherever you are.
May 20th, 2009 at 5:50 pm
Не бойся незнания, бойся ложного знания. От него все зло мира.
May 21st, 2009 at 5:54 am
Более 3х лет регулярно работаю над этой проблемой и считаю ваши мысли особо легкомысленными
May 22nd, 2009 at 8:11 pm
Где то около 2х лет регулярно обеспокоен этой тематикой и думаю ваши идеи достаточно легкомысленными
May 25th, 2009 at 4:48 pm
Айс
May 29th, 2009 at 11:18 pm
plant in house
June 1st, 2009 at 6:55 pm
Аффтар какбе намекает что в риллайве все пидоры, юзернейм, и нет пути, совсем нет(((
June 1st, 2009 at 7:22 pm
red sea
June 2nd, 2009 at 9:38 pm
birthday gift
June 5th, 2009 at 11:48 am
If you’re a blogger (or a blog reader), you’re painfully easy with people who try one’s hand at to engender their own websites’ search apparatus rankings by submitting linked blog comments like “Take in my discount pharmaceuticals site.” This is called animadversion spam, we don’t like it either, and we’ve been testing a stylish name that blocks it. From right now on, when Google sees the property (rel=”nofollow”) on hyperlinks, those links won’t get any ascription when we rank websites in our search results. This isn’t a negative guarantee for the place where the remark was posted; it’s honest a manner to make sure that spammers injure no benefit from abusing exposed areas like blog comments, trackbacks, and referrer lists.
June 9th, 2009 at 8:07 am
Чем меньше люди знают, тем обширнее кажется им их знание.
June 14th, 2009 at 3:50 am
The article is ver good. Write please more
June 22nd, 2009 at 9:48 am
Very good message
June 22nd, 2009 at 12:35 pm
Ada yang bersedih,..tentunya ada yang bergembira dengan kekalahan perancis,…termasuk saya yang bergembira,…Bravo Italy
Slam kenal Bang
June 23rd, 2009 at 2:57 pm
ZnQJJR comment2 ,
June 23rd, 2009 at 9:24 pm
Thanks dude, it really helps. I owe you a beer.
June 23rd, 2009 at 9:30 pm
I’m new to the site and just purchased lots of items last night, and still have not received an email with the items.
How long does it normally take to get the items? I understood that as soon as I paid everything would be emailed
to me. Just wondering……
Thanks
June 24th, 2009 at 3:51 pm
hi
where do add
$sql = “SELECT username FROM users WHERE username=’$username’”;
if($sql) {
echo “Username already exists”;
} else {
echo “Username doesn’t exist”;
}
to which php ??
June 25th, 2009 at 1:06 pm
думаю вы как обычно лжёте
June 26th, 2009 at 9:45 am
Народ в таких вот случаях говорит – ахал бы дядя, на себя глядя.
July 1st, 2009 at 12:49 am
Кайтсерфинг, школа кайтсерфинга, обучение кайтсерфингу,кайтинг, кайтинг обучение, кайт школа, кайт школа вьетнам.
July 3rd, 2009 at 12:10 am
Personal messages at all today send?