So far we’ve made our database, connected to it, and wrote a function to get rid of
SQL Injection attempts. Now we can make the registration page.
We’ll have a form with a couple fields and a submit button that sends everything to our database.
The first thing we’re going to do is include the db_connect.php page. This will connect us to our database and give us access to the protect function we created earlier.
This form will then submit to itself and insert the data into our db.
<?php //Create registration form (register.php) include "db_connect.php"; if(!$_POST['submit']) // 'submit' hasn't been clicked so output html. { ?>
So what the first IF statement does is checks to see if the form has been submitted. If it hasn’t it outputs the html form.
<html> <form method="post" action="register.php"> First Name: <input type="text" name="first"> Last Name: <input type="text" name="last"> Desired Username: <input type="text" name="username"> Password: <input type="password" name="password"> Confirm Password: <input type="password" name="pass_conf"> Email: <input type="text" name="email"> About: <textarea name="about">Tell us about yourself</textarea> <input type="submit" name="submit" value="Register"> </form> or <a href="index.php">Login</a> </html>
Notice the forms action is register.php which is the page itself. When ‘submit’ is posted we go to the else block here. This is where we store the posted values into variables. We call our protect function on these values to cleanse them of any injection attempts.
<?php } else { $first = protect($_POST['first']); $last = protect($_POST['last']); $username = protect($_POST['username']); $password = protect($_POST['password']); $pass_conf = protect($_POST['pass_conf']); $email = protect($_POST['email']); $about = protect($_POST['about']);
Now that we have the values the user entered, we can do some error checking. We’ll create an errors array and add an error message for every error that occurs to the array. The first one makes sure the email is in a valid name@domain format using regular expressions.
$errors = array(); $regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*@([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i"; if(!preg_match($regex, $email)) { $errors[] = "E-mail is not in name@domain format!"; }
The next block makes sure all of the fields have been filled out.
if(!$first || !$last || !$username || !$password || !$pass_conf || !$email || !$about) { $errors[] = "You did not fill out the required fields"; }
This makes sure the passwords match
if ($password != $pass_conf) { $errors[] = "Your confirmed password does not match you initial password"; }
Now we need to make sure the username this user wants isn’t already taken. To do this we’ll take the username they submitted and look for it in our db. If we find it, that username is taken so we output an error message.
$sql = "SELECT * FROM `users` WHERE `username`='{$username}'"; $query = mysql_query($sql) or die(mysql_error()); if(mysql_num_rows($query) > 0) { $errors[] = "Username already taken, please try another"; }
Heres where we loop through our errors array and output everything that went wrong with the registration.
if(count($errors) > 0) { echo "The following errors occured with your registration"; echo "<font color="red">"; foreach($errors AS $error) { echo $error . "\n"; } echo "</font>"; echo "<a href=\"javascript:history.go(-1)\">Try again</a>"; //we use javascript to go back rather than reloading the page // so the user doesn't have to type in all that info again. }
If nothing went wrong we insert the new information into our database using SQL queries.
else { $sql = "INSERT into `users`(`first`,`last`,`username`,`password`,`email`,`about`) VALUES ('$first','$last','$username','".md5($password)."','$email','$about');"; $query = mysql_query($sql) or die(mysql_error()); echo "Thank You for registering {$first_name}! Your username is {$username}"; echo "<a href="index.php"> Click here </a> to Login"; } } ?>
So now that the user is registered, they need a place to login.
We’re going to use the same if(!$_POST['submit']) idea. If submit hasn’t posted, output the html. If it has, query the database. We use the session_start() function to create a session. Once a login is succesful we can create session variables to reference this specific user for their session. This will come in handy in the next tutorial when we need to get this users pictures from the database. You can find more info on php sessions here.
<?php session_start(); //Login form (index.php) include "db_connect.php"; if(!$_POST['submit']) { ?> <html> <b><Login</b> <form method="post" action="index.php"> Username<input type="text" name="username" maxlength="16"> Password<input type="password" name="password" maxlength="16"> <input type="submit" name="submit" value="Login"> </form> <a href="register.php">Register Here</a> </html>
Ok here we’re going to make sure both the username and password were entered. Then we’ll query our db with the posted values to see if theres a match. If there is, we create our session variables (to be used later) and take the user to their homepage. If the database couldn’t find anything we output an incorrect login message.
<?php } else { $user = protect($_POST['username']); $pass = protect($_POST['password']); if($user && $pass) { $pass = md5($pass); //compare the encrypted password $sql="SELECT id,username FROM `users` WHERE `username`='$user' AND `password`='$pass'"; $query=mysql_query($sql) or die(mysql_error()); if(mysql_num_rows($query) == 1) { $row = mysql_fetch_assoc($query); // mysql_fetch_assoc gets the value for each field in the row $_SESSION['id'] = $row['id']; //creates the first session var $_SESSION['username'] = $row['username']; // second session var echo "<script type="text/javascript">window.location="home.php"</script>"; } else { echo "<script type="text/javascript"> alert("Username and password combination is incorrect!"); window.location="index.php"</script>"; } } else { echo "<script type="text/javascript"> alert("You need to gimme a username AND password!!"); window.location="index.php"</script>"; } } ?>
Now we need a place for our user to go to when they login successfully. Make another php file and call it “home.php”
<?php session_start(); //home.php if($_SESSION['id']) { echo "Welcome ",$_SESSION['username'] ; echo " <a href="logout.php">Logout</a>" ; } else { echo "You don't belong here!"; } ?>
Finally we create a logout page which destroys our session.
<?php session_start(); //logout (logout.php) include "db_connect.php"; if($_SESSION['id']) { session_destroy(); echo "<script type="text/javascript"> alert("You have logged out"); window.location="index.php"</script>"; } ?>
That’s it for part 2. Check out Part 3 to learn how to allow the user to update their profile and add pictures.


#1 by Pranav on January 20, 2009 - 10:30 pm
I find this very useful for a beginner of PHP. Good job Bhavik, and thank you for the information. Looking forward to see some advanced tutorials in future.
Thanks,
Pranav
#2 by James on February 21, 2009 - 5:43 pm
Very useful and well explained tutorial. I look forward to the next part. When is part 3 out?
#3 by Bhavik on February 22, 2009 - 12:44 pm
Hey James, I’m glad you liked the tuts. I was planning on going over security related things before part 3 of the PHP. Since you’re looking forward to part 3 I can finish that up first. Look for it within the next couple of days. Thanks for reading!
#4 by James on February 22, 2009 - 1:11 pm
You’re a star Bhavik, thanks!
#5 by James on February 22, 2009 - 1:12 pm
Oh, i sent you over another question through the contact form!
#6 by pootzko on April 3, 2009 - 6:55 pm
you need a backslash when using tags in echo. errors are in echo “”; and echo “
thnx for the tutorial
#7 by Vasya on April 8, 2009 - 11:42 am
thnx for this tutorial! It very useful for me and helps me to understand functions and their apply)) Sorry for the mistakes… I am from Ukraine!
#8 by Bhavik on April 8, 2009 - 6:30 pm
Your Welcome Vasya, Thanks for reading!
#9 by Boris on April 12, 2009 - 1:47 pm
You have a huge security hole buddy:
I might be wrong, but what if $_SESSION['id'] is already defined through another site?
Let’s say there are two different sites that use this same script (they both check if $_SESSION['id'] is defined to allow users to view the page). So I have a login for the first site, but I don’t have access to the second one. All I need to do is login to the first site, and then go to the second site (without logging out) and because the session is already defined, it will allow me in. Am I right?
#10 by Bhavik on April 12, 2009 - 2:11 pm
I probably have many more security holes too, this isn’t code that you’d wanna use in a live environment. Just a way to learn php.
It’s good that you mentioned it though. Its definitely something I’ll play with later tonight and see if its an actual hole. Nice catch!
I’ll post back tomorrow and let you know the results. Thanks Boris.
#11 by Zan on April 13, 2009 - 12:33 pm
It doesn’t matter if two pages have same sesion[id]s. That’s the thing about sessions.. they’re stored on the server not the clients machine.
On the other hand, thanks for the great guide.
#12 by Bhavik on April 13, 2009 - 12:38 pm
Thanks for clearing that up Zan!
#13 by Erik on April 14, 2009 - 5:50 am
Hi,
Thanks a lot for the tutorials!!
There’s one weird thing, on register.php on the bottom it already shows the errors without doing anything!
(withe errors i mean you did not fill out youre password and stuff like that, fill out all the fields)
gr. Erik
#14 by Bob Harris on April 15, 2009 - 4:44 pm
You know, one thing that people should start right off the bat is parameterizing queries and quit this string concatenation nonsense. That would be a fantastic tutorial.
#15 by Bhavik on April 15, 2009 - 8:19 pm
Hey Bob, Yeah the string concatenation is a bit messy…When I was teaching myself PHP I didn’t even know you could parameterize queries. Just knew that the mysql_query function took a string so thats what I gave it. Thanks for the suggestion on the tutorial, I’ll see what I can come up with
#16 by Muss on April 25, 2009 - 7:28 am
There is always an undefined index on top of my login and registration page.
the error on the login page is : UNDEFINED INDEX SUBMIT which is this line: if (!$_POST['submit']){ print the html page with the login}
And the same error for the registration appears on top of the page.
can anyone help me please to get rid of the UNDEFINED INDEX submit?
#17 by bill gates on April 28, 2009 - 7:24 am
For beginners, I suggest changing this code:
if(mysql_num_rows($query) > 0)
to this:
if(mysql_num_rows($query) == 1)
Because you only want a single result from the DB for the submitted username/password. If you get more than one record, there’s a problem. Check for that and handle it with an error message.
Also, please don’t echo nifty javascript pop-ups, etc. Just echo the error on the page. Someone can turn off javascript and not see the error messages. So get out of the habit of using javascript for error messages and most importantly don’t use it for FORM VALIDATION.
On the login page, kill the session if there’s no submit.
#18 by Bhavik on April 28, 2009 - 10:27 am
Thank you for your suggestions Mr. Gates,
You’re right about the if statement, it should be
As for the javascript, again this login system is to help people learn PHP… not to use in a live environment. It isn’t a ‘habit’.
#19 by amer on May 2, 2009 - 1:26 pm
nice tutorial thanks
#20 by nvr87 on May 15, 2009 - 5:46 pm
Thank you for this great tutorial. Have 1 problem though, (probably a dumb mistake by me)
as soon as i want to log in it keeps saying you don’t belong here.
The login forwards me to home.php because the usrnm and pass are correct
buth the home.php doesnt recognize the session and still blocks me out.
Any ideas of how this could’v happened?? Pretty new on the PHP stuff….
#21 by nvr87 on May 16, 2009 - 2:54 am
Hi sorry to bother you, i’ve found the error….
Dumb mistake by me as i thought haha, needed to log out because there
was something wrong with the session, now it works fine haha….
Th4nks 4g41n f0r th1s gr347 7u70r14l !!!!!!
#22 by Bhavik on May 17, 2009 - 6:01 pm
Hey nvr87, glad you figured it out
#23 by Justin on May 22, 2009 - 8:38 am
I don’t understand why I cannot login with new accounts I created manually using myphpadmin, do I have to create the accounts using the method above before I can log into them or? It keeps telling me Username and Password are incorrect.
NB. I make sure I choose MD5 from the drop down when creating the password.
#24 by Bhavik on May 22, 2009 - 2:32 pm
Hey Justin, I don’t see why you can’t login either. It must be an issue when comparing the encrypted strings. Are your fields long enough? Maybe the database field is cutting the hash shorter, which would make them to not be equal. Check to see how many characters your password field holds and the characters of the hashed string. Does it work when you register through the actual registration page?
#25 by Shane on June 27, 2009 - 12:13 pm
Hi – excellent tutorial!
I am haveing one issue though, when the login page loads I am getting the following ‘notice’ at the top of the screen:
Notice: Undefined index: submit in C:\wamp\www\Login.php on line 4
That line relates to the code if(!$_POST[submit]) line in the file – it doesn’t seem to like it.
Any ideas?
#26 by Shane on June 27, 2009 - 12:15 pm
I left the ‘s out around submit on my post here – it is in the script though…
#27 by Shane on June 27, 2009 - 1:57 pm
Sorted it, finally
it was an issue with the submit button properties and I changed the line mentioned above to
if(!isset($_POST['submit']);
and all works fine now
#28 by Clark on July 2, 2009 - 11:38 am
Hey, is there a way to download these files, like db_connect.php, register.php, login.php etc. It would be really helpful. Thanks.
#29 by Bhavik on July 2, 2009 - 11:55 am
Hey Clark, I offer all the source as a zipped download on the last part (part 3) of the tutorial.
#30 by skerit on August 21, 2009 - 5:36 am
I’m having a problem with the index.php page.
I tried to add a section, which loads the jquery library.
But for some reason it won’t validate the “if(!$_POST['submit'])” anymore, it doesn’t give me any way to log in.
[CODE]
<Login
Username
Password
Register Here
<?php
[/CODE]
#31 by skerit on August 21, 2009 - 5:39 am
Ah, apparently your comments execute html code.
#32 by chocorobokun on May 31, 2010 - 11:56 pm
Thanks for the great tuts man
now i can make my own login system from
scratch with php,based on this tutorial
looking forward for your next php tutorial!!!
#33 by Bridget on June 7, 2010 - 1:57 am
Hi there! Great tutorial! I tried it out just as you have it and tweaked it to fit a project I’m doing for an advanced php course.
My problem arises on the index.php (signin.php for mine). I registered a test user and it registers, but when I sign in, it says, to gimme a username and password. I did have maxlengths in the input fields but took them out, took the md5 code out and then replaced it. I’ve compared line for line. The only difference is I used a table and you used div layers.
I’m baffled. I guess I’ll try using div layers, maybe for some reason that will fix the boo-boo I keep getting?
#34 by Bridget on June 9, 2010 - 3:20 pm
Well, I finally got it to work and this is great! I’m still learning PHP and I’ve learned it’s all trial and error.
I do have a question though. What if you want to pull the information you’ve inputted from the users and create a gallery? I learned how to do it thru lynda.com but that’s for a single user. I’ve tried every possible way I can think of but to no avail. I have a galleries.php file as well as image_script.php file. I know the image_script.php file pulls the information from the database and it displays in galleries.php but how do you call the folders in which the users images are displayed?