Jump to content
xisto Community
MiniK

Simple Php Login And Registration System

Recommended Posts

Hello. This is my first web tutorial ever. This is basically a simple register and login script. Yes, I know its a bit rubbish but Im quite new to PHP/MySQL.

 

Heres the register form. This can be any file extension you like. Id recommend calling it register.html.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd;<html xmlns="http://www.w3.org/1999/xhtml/;<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Register</title></head><body><h1>Register</h1><table><tr><form action=register.php method=post><td width="81">Username:</td><td width="247"><input name="username" size="30" autocomplete="off" value="" type="text" /></td></tr><tr><td>Password:</td><td><input name="password" size="30" type="password" /></td></tr><tr><td>First Name:</td><td><input name="firstname" size="30" type="text" /></td></tr><tr><td>Last Name:</td><td><input name="lastname" size="30" type="text" /></td></tr><tr><td>Age:</td><td><input name="age" size="30" maxlength="2" /></td></tr></table><p><input type="submit" class="button" value="Register" /></p></form></body></html>

Now create a MySQL database. Then create a file that will be called
mysql-connect.php
. Here is the file:

 

<?php$con = mysql_connect("DB_HOST","DB_USER","DB_PASS");mysql_select_db("DB_NAME", $con);?>

Replace DB_HOST with the host of your database. This is usually localhost, but some hosts differ. Replace DB_USER with the username for your database, and DB_PASS with the password of your database and then replace DB_NAME with the name of your database. Enough with this file, lets get onto the actual registration script. Save this as
register.php
.

 

<?phpinclude 'mysql-connect.php';$username = $_POST['username'];$password = $_POST['password'];$firstname = $_POST['firstname'];$lastname = $_POST['lastname'];$age = $_POST['age'];$ip = $_SERVER['REMOTE_ADDR'];$result = mysql_num_rows(mysql_query("SELECT * FROM TABLENAME WHERE username='$username'"));if($result == 1)	{	echo <h1>ERROR!</h1>The username you have chosen already exists!;	}else	{	mysql_query("INSERT INTO TABLENAME (username, password, firstname, lastname, age, ip) VALUES ('$username', '$password', '$firstname', '$lastname', '$age', '$ip')");	echo '  <p>Congratulations! You have successfully registered! </p>  <p>Click <a href="login.php">here</a> to login.</p>;?>

OK, lets break this down:

 

include 'mysql-connect.php';

Include the database connection file.

 

$username = $_POST['username'];$password = $_POST['password'];$firstname = $_POST['firstname'];$lastname = $_POST['lastname'];$age = $_POST['age'];$ip = $_SERVER['REMOTE_ADDR'];

This part gets all of the variables: username, password, first name, last name, age and ip address.

 

$result = mysql_num_rows(mysql_query("SELECT * FROM TABLENAME WHERE username='$username'"));

This checks to see if the username already exists in the database. Make sure you change TABLENAME to the name of the table in which the user information is stored.

 

if($result == 1)	{	echo <h1>ERROR!</h1>The username you have chosen already exists!;	}else	{	mysql_query("INSERT INTO TABLENAME (username, password, firstname, lastname, age, ip) VALUES ('$username', '$password', '$firstname', '$lastname', '$age', '$ip')");	echo '  <p>Congratulations! You have successfully registered! </p>  <p>Click <a href="login.php">here</a> to login.</p>;

If the username already exists, display an error message, and if not, insert the user information into the database and display a login link. Make sure you change TABLENAME to the name of the table in which the user information is stored. Now onto the login form. This is quite simple. Just save it as login.php.

 

<html><head><title>Login</title></head><body><form name="login" action="login2.php" method="post"><table align="center"><tr><td class="title">Username</td><td><input name="user" size="30" autocomplete="off" value="" type="text" /></td></tr><tr><td class="title">Password</td><td><input name="pass" size="30" type="password" /></td></tr></table><p style="text-align:center;"><input type="submit" class="button" value="Login" /></p></form></body></html>

Basically, that asks for username and password, and sends them to another file called
login2.php
which we shall move onto now

 

<?phpinclude 'mysql-connect.php';$username = $_POST['user'];$password = $_POST['pass'];$query1 = mysql_query("SELECT * FROM TABLENAME WHERE username='$username'");$result = mysql_num_rows($query1);if($result == 0){include '<h1>Error!</h1>The username you specified does not exist!';}else{$checkuser = mysql_query("SELECT * FROM TABLENAME WHERE username='$username'");			$row = mysql_fetch_array($checkuser);							$password2 = $row['password'];							$status = $row['status'];				if ($password == $password2)					{					//PUT PASSWORD PROTECTED INFORMATION HERE					}				else					{					echo '<h1>Error!</h1>The username and password combination you entered does not match the ones we have in the database.';					}}?>

Lets break this file down aswell.

$username = $_POST['user'];$password = $_POST['pass'];

This grabs the username and password that they entered.

 

$query1 = mysql_query("SELECT * FROM TABLENAME WHERE username='$username'");$result = mysql_num_rows($query1);

This checks to see if the user exists in the database. Make sure you change TABLENAME to the name of the table in which the user information is stored.

 

if($result == 0){include '<h1>Error!</h1>The username you specified does not exist!';}

If not, display an error message.

 

else{$checkuser = mysql_query("SELECT * FROM TABLENAME WHERE username='$username'");			$row = mysql_fetch_array($checkuser);

If the user does exist, get the information stored in the database about that user. Make sure you change TABLENAME to the name of the table in which the user information is stored.

 

$password2 = $row['password'];

Get the users password.

 

if ($password == $password2)				{				//PUT PASSWORD PROTECTED INFORMATION HERE				}

If the password in the database matches the one they entered, display password protected information.

 

else				{					echo '<h1>Error!</h1>The username and password combination you entered does not match the ones we have in the database.';				}}

If not, display yet another error message.

 

OK, thats the script. Hope you liked it. It was for a website I was making but I have no need for it anymore, so I thought I would post it here so that other people can learn from it. :P This /should/ work, but if it doesn't, just let me know and I can advise you on what is wrong and can edit it. We can ALL learn from our mistakes.

Share this post


Link to post
Share on other sites

Hello,I'm new to PHP myself and have what I hope is a basic question. I'd like to have password protected pages on my site. Simple have no more than 10 pages, each one with its own password. Is this doable with PHP, do I need MySQL installed for that? Furthermore, if I see a server like the one provided by Xisto.com how can I install my PHP script on it?

Share this post


Link to post
Share on other sites

You mention in the end, that this system is for the purpose that other peoples can/will learn from it - To be honest, if I was new to PHP/MySQL, I wouldn't understand half of it. I think you should comment more what the codes do, give a little bit description.But good job on making it, I guess.

Share this post


Link to post
Share on other sites

Thanks for this tutorial!

I'm just starting with MySQL, and I actually understood everything.

Great job!

EDIT: Never mind that last question, found the answer.

Another question thought, I'm getting this error when I run the script (after correcting all the other errors):

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/gaiazone/public_html/mysql/login2.php on line 7

All my problems seem to be with that command.

Any help?
Edited by GaiaZone (see edit history)

Share this post


Link to post
Share on other sites

Hello,
I'm new to PHP myself and have what I hope is a basic question. I'd like to have password protected pages on my site. Simple have no more than 10 pages, each one with its own password. Is this doable with PHP, do I need MySQL installed for that?

Furthermore, if I see a server like the one provided by Xisto.com how can I install my PHP script on it?


Am am not totally sure how to do this, but I know it has something to do with the .htaccess file. I will search it up in a sec and get it back to you.

Back on Topic- This is a very nice tutorial, I am needing one of these for my site. Do you mind if I adjust it so it can be a login for my forum, instead of a site?

Thanks,

Imtay

Share this post


Link to post
Share on other sites

Thanks for this tutorial!
I'm just starting with MySQL, and I actually understood everything.

Great job!

EDIT: Never mind that last question, found the answer.

Another question thought, I'm getting this error when I run the script (after correcting all the other errors):
All my problems seem to be with that command.

Any help?



mby u forgot or did anything wrong in the connection of mysql db.. or else mby iu forgot to change table name or somthing =D

Share this post


Link to post
Share on other sites

Hello I must say that this is good tutorial however there are few things to attent first of all write more comments user secure password and name all your files with the .php extension instead of html because if you have some code in the html file it will not be executed on the server.And the other question to attend. PHP and MySQL are already installed when you obtain your account on Xisto. sO don't worry about it especially if you are beginner.

Share this post


Link to post
Share on other sites

I'd like to have password protected pages on my site. Simple have no more than 10 pages, each one with its own password.

Am am not totally sure how to do this, but I know it has something to do with the .htaccess file. I will search it up in a sec and get it back to you.

Step 3. Add Access Files to the FolderOnce you identify the folder you wish to safeguard, then you need to create two files in this folder. The files are: .htaccess and .htpasswd. The .htaccess file displays the access login information needed for users and also includes the list of specific users who can login. The .htpasswd file includes the individual users and their passwords.

Create .htaccess file in your Folder by using a text editor to create .htaccess. Notice that you must include the . (dot) before the file name!

The file should atleast include these lines:
AuthName "Login to the Private Area"
AuthType Basic
AuthUserFile /var/www/html/Private/.htpasswd
Require user andrea

Note that the AuthName requires quotes and whatever is in quotes will display on the login window when a user tries to access your private folder with a web browser. It is vital that you properly set the path for the AuthUserFile and obviously replace the word Private with whatever folder you are trying to password protect.

Also be sure to include the user login names of the people you plan to allow to this folder next to the Require user line. In my case, I simply added myself to this folder as a user (andrea).

Now, create the .htpasswd file in the same Folder but NOT by using a text editor. Instead use this command from the command line on your Linux server.

Type this command at the prompt:
htpasswd -cmb .htpasswd andrea ann2cute

Note that you must use your own name and password (replace andrea and ann2cute) and that the option cmb does the following: First it forces Creating of a new .htpasswd file. Since this is your first time adding a user it is necessary. Next the m option forces encryption and b allows you to include the user name and password immediately. In my case I created a new .htpasswd file, then added the user andrea and her password ann2cute.


That explains how to do that. If you need any help please visit the whole guidehere.

Thanks,

Imtay

Share this post


Link to post
Share on other sites

I thought that this guy in fact wanted the php scripts to protect that is password protect thouse pages. However I might have misunderstood in the end. And that the guy answering to his question in fact said that it migt be done using htaccess file.

Share this post


Link to post
Share on other sites

im trying to allow users to comment only if they are registered. this is what i got for my code but somewhere i went wrong and it doesnt show you must be registered to leave comment, and when logged in it wont show the comment box... i know i went wrong at the if user logged in =1 but i cant find.


<?php  require_once ('database_connect.php');//query comments for this page of this article $inf = "SELECT * FROM `comments` WHERE page = '".stripslashes($_SERVER['REQUEST_URI'])."' ORDER BY time ASC"; $info = mysql_query($inf); 	 if(!$info) die(mysql_error());    $info_rows = mysql_num_rows($info); if($info_rows > 0) {    echo '<h5>Comments:</h5>';    echo '<table width="95%">'; 	while($info2 = mysql_fetch_object($info)) {	 echo '<tr>';	echo '<td>"'.stripslashes($info2->subject).'" by: <a href="'.$info2->contact.'">'.stripslashes($info2->username).'</a></td> <td><div align="right"> @ '.date('h:i:s a', $info2->time).' on '.$info2->date.'</div></td>'; echo '</tr><tr>'; echo '<td colspan="2"> '.stripslashes($info2->comment).' </td>'; echo '</tr>'; }//end while echo '</table>'; echo '<hr width="95%" noshade>'; } else echo '<br>'; if(isset($_POST['submit'])) {   if(!addslashes($_POST['username'])) die('<u>ERROR:</u> you must enter a username to add a comment.');   if(!addslashes($_POST['contact']))  die('<u>ERROR:</u> enter contact method in contact field.');   if(!addslashes($_POST['subject']))  die('<u>ERROR:</u> enter a subject to your comment.');   if(!addslashes($_POST['comment']))  die('<u>ERROR:</u> cannot add comment if you do not enter one!?'); //this is for a valid contact   if(substr($_POST['contact'],0,7) != 'mailto:' && !strstr($_POST['contact'],'//')) { 			  if(strstr($_POST['contact'],'@')) 				$_POST['contact'] = "mailto:".$_POST['contact'].""; 			  else 				$_POST['contact'] = "http://".$_POST['contact']."";    } //end valid contact //try to prevent multiple posts and flooding... $c = "SELECT * from `comments` WHERE ip = '".$_SERVER['REMOTE_ADDR']."'";   $c2 = mysql_query($c); 	 while($c3 = mysql_fetch_object($c2)) { 	  $difference = time() - $c3->time; 	 if($difference < 300) die('<u>ALERT:</u> '.$c3->username.', You have already commented earlier!<BR>'); 	  } //end while //add comment $q ="INSERT INTO `comments` (article_id, page, date, time, username, ip, contact, subject, comment) VALUES ('".$_GET['id']."', '".$_POST['page']."', '".$_POST['date']."', '".$_POST['time']."', '".addslashes(htmlspecialchars($_POST['username']))."', '".$_SERVER['REMOTE_ADDR']."', '".addslashes(htmlspecialchars($_POST['contact']))."', '".addslashes(htmlspecialchars($_POST['subject']))."', '".addslashes(htmlspecialchars(nl2br($_POST['comment'])))."')"; $q2 = mysql_query($q);   if(!$q2) die(mysql_error()); //refresh page so they can see new comment header('Location: http://link to page' . $_SERVER['HTTP_HOST'] . $_POST['page'] . "#comments"); //user must be logged inif($_SESSION['logged_in'] == 1) {?><h3 id="respond">Leave a Reply</h3><br><form name="comments" action="<? $_SERVER['PHP_SELF']; ?>" method="post"> <input type="hidden" name="page" value="<? echo($_SERVER['REQUEST_URI']); ?>"> <input type="hidden" name="date" value="<? echo(date("F j, Y.")); ?>"> <input type="hidden" name="time" value="<? echo(time()); ?>"> <table width="90%" border="0" cellspacing="0" cellpadding="0">    <tr> 	  <td><div align="right">Username:   </div></td> 	   <td><input name="username" type="text" size="30" value=""></td>    </tr> 	<tr> 	  <td><div align="right">Contact:   </div></td> 	  <td><input type="text" name="contact" size="30" value=""> <i>(email or url)</i></td> 	</tr> 	<td><div align="right">Subject:   </div></td> 	<td><input type="text" name="subject" size="30" value=""></td> 	</tr> 	<tr> 	  <td><div align="right">Comment:   </div></td> 	  <td><textarea name="comment" cols="45" rows="5" wrap="VIRTUAL"></textarea></td> 	</tr> 	<tr> 	  <td></td> 	  <td colspan="2"><input type="reset" value="Reset" style="background: #2c2c2c; font-family: vrinda; color: white; border: 0; width:80; height= 20;">	  		<input type="submit" name="submit" value="Add Comment" style="background: #2c2c2c; font-family: vrinda; color: white; border: 0; width:80; height= 20;"></td> 	</tr>   </table> </form><?php} else {if($_SESSION['logged_in'] == 0) echo ('You must be a registered member to comment'); }}?>


if anyone could help me please. this is the main problem im having with my page.

Share this post


Link to post
Share on other sites

help please

It'd help alot more if you tell us what exactly you are wanting help with. :lol:
@ miniK: Brilliant script MiniK. This will be very useful for people and their websites/forums etc! ^_^

-Sky

Share this post


Link to post
Share on other sites

I have comments on a page and i want them to be viewable by everyone but only registered members are allowed to post. What else i was toing for was when a member posts it inserts the usersname into the post automatically.

 

I have my member login made and my comments, i'm trying to get the IF and the ELSE right to combine the comments with the member login.

 

I hope what i explained is understanding Posted Image

 

I could also display my cookies i have at the top of my script as well if it is needed.

Share this post


Link to post
Share on other sites

Im new to PHP, and I can say I understood bits of it. Some areas I think could have said an explaination of the code, but still great job! When I understand PHP a little more, Ill come back to this Tutorial and try again. Thanks for posting! :lol:

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.