Simple Php Login And Registration System

Pages: 1, 2
free web hosting

Read Latest Entries..: (Post #15) by roym on Sep 27 2008, 10:59 AM. (Line Breaks Removed)
I could also display my cookies i have at the top of my script as well if it is needed.
Read the FIRST post of this Topic. - Express your Opinion! Contribute Knowledge :-).

Open Discussion > CONTRIBUTE > Tutorials

Simple Php Login And Registration System

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

Here’s the register form. This can be any file extension you like. I’d recommend calling it register.html.

CODE
<!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
CODE
mysql-connect.php
. Here is the file:

CODE
<?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, let’s get onto the actual registration script. Save this as
CODE
register.php
.

CODE
<?php
include '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, let’s break this down:

CODE
include 'mysql-connect.php';


Include the database connection file.

CODE
$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.

CODE
$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.

CODE
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.

CODE
<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
CODE
login2.php
which we shall move onto now…

CODE
<?php
include '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.';
                    }

}
?>


Let’s break this file down aswell.
CODE
$username = $_POST['user'];
$password = $_POST['pass'];


This grabs the username and password that they entered.

CODE
$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.

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


If not, display an error message.

CODE
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.

CODE
$password2 = $row['password'];


Get the user’s password.

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


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

CODE
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, that’s 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. wink.gif 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.

 

 

 


Reply

karlosvalencia
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 trap17.com how can I install my PHP script on it?

Reply

Acid
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.

Reply

coldasice
any ways.. use md5($password) for secure password smile.gif

Reply

GaiaZone
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):

QUOTE
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?

Reply

Imtay22
QUOTE(karlosvalencia @ Jan 5 2008, 08:35 AM) *
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 trap17.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

Reply

coldasice
QUOTE(GaiaZone @ Jan 10 2008, 11:37 PM) *
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

Reply

hitmanblood
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 trap17. sO don't worry about it especially if you are beginner.

Reply

Imtay22
QUOTE(Imtay22 @ Jan 13 2008, 07:53 AM) *
QUOTE
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.



QUOTE
Step 3. Add Access Files to the Folder
Once 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

 

 

 


Reply

hitmanblood
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.

Reply

Latest Entries

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

Reply

roym
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 smile.gif

Reply

-Sky-
QUOTE(roym @ Sep 26 2008, 09:52 PM) *
help please

It'd help alot more if you tell us what exactly you are wanting help with. smile.gif

@ miniK: Brilliant script MiniK. This will be very useful for people and their websites/forums etc! smile.gif

-Sky

Reply

roym
help please

Reply

roym
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.


CODE
<?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 in
if($_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.

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.

Pages: 1, 2
Recent Queries:-
  1. sample of php codes registration - 9.17 hr back. (1)
  2. login system with html - 14.17 hr back. (1)
  3. php registration database - 18.35 hr back. (1)
  4. php registration script - 33.30 hr back. (1)
  5. registration system php - 379.72 hr back. (1)
  6. simple php registration with file - 404.58 hr back. (1)
  7. register - 414.43 hr back. (1)
  8. sample php registration system - 552.21 hr back. (1)
  9. simple php registration - 407.95 hr back. (3)
  10. simple login-logoff & registration script in php - 640.98 hr back. (3)
  11. php: registration system - 656.30 hr back. (1)
  12. php registration system - 156.43 hr back. (2)
  13. job registration system php - 1026.48 hr back. (1)
Similar Topics

Keywords : simple, php, login, registration, system

  1. To Automatically Run Command When Login / Logoff
    (3)
  2. Automatic Login
    in WinXP (5)
    Ever wanted to just turn on our computer and when you get back it's already on the desktop?
    (Rather then having to login at the welcome screen) Now some computer have this feature by default,
    but what if it gets broken, try this. On an Administrator account goto start >> Run, and type
    "control userpasswords2" (without the quotes) Uncheck the box that "Users must enter a Username and
    Password to use this computer", then press Ok. You will be prompted to enter a default user and
    their pasword, then next time you restart the computer it will automaticaly login to that....
  3. Simple Login In Visual Basic 6
    user interaction example trough login programm (6)
    First of all, I am NOT a programmer, this is something my friend taught me. It describes basic
    interaction with the user, while showing basic functionality of this simple programm. So, without
    further ado, we're off to the tutorial: First of all, start your visual basic, when prompted
    for new project, select Standard Exe . Next, we need to open code window, so we can start typing
    the program. This can be done in two ways, one is double clicking on the form, or selecting Code
    from View menu. If you double clicked on the form, you will see following text: CODE ....
  4. How To Put A Phpbb Login Box On Your Main Site.
    Code and .php included!!! (18)
    I have included my coded file with this... Ok here is the code. CODE // //Create login area,
    replace the phpBB2 in /phpBB2/login.php with your forum's //directory // <form
    action="/phpBB2/login.php" method="post" target="_top"> <table
    width="25%" cellspacing="2" cellpadding="2" border="0"
    align="center">  <tr> <td align="left"
    class="nav"><a href="/phpBB2/index.php" class="nav">Prank Place
    Forum Index</a></td>....
  5. Php/mysql Login/register
    Tutorial for login with databases. (2)
    Start register code. Register.php CODE <form method=post
    action=register.php?action=register  name=s> <table>
    <tr><td>Username:</td><td><input type=text
    name=user></td></tr>
    <tr><td>Email:</td><td><input type=text
    name=email></td></tr>
    <tr><td>Pass:</td><td><input type=password
    name=pass></td></tr> <tr><td>Verify
    Pass:</td><td><input ....
  6. Complete Login And Registration System
    doesn't use mysql! (9)
    kLogin 0.1 QUOTE(readme.txt) Readme file to kLogin 0.1 To use the internet explorer fix:
    download the latest IE7 ZIP file
    (http://sourceforge.net/project/showfiles.php?group_id=109983&package_id=119707) Extract the ie7
    zip file to the root directory of your web server. Example, if you are using a unix/linux server,
    it's on "public_html/" or "home/public_html" Open kLogin.php file with your editor and edit the
    $info_text or $info_txt variable. Then, extract the kLogin.php file in to the root
    directory of your web server also. Just run kShoutBo....
  7. Multiple Admin Login (php)
    This is a script that doesnt requre SQL (3)
    first off make a login.html page Code: QUOTE Admin Login Username: Password:
    then make a check.php page Code: QUOTE $admin1 = "admin1"; //
    first admin username $adm_pass1 = "password1"; // first admin password $admin2 =
    "admin2"; // second admin username $adm_pass2 = "password2"; // second admin password
    if(($username == $admin1 && $password == $adm_pass1) || ($username ==
    $admin2 && $password == $adm_pass2)){ echo "Congratulations " . $_POST . " ....
  8. Php Simple Login Tutorial
    Learn how to make a simple login! (63)
    I have been quite busy lately, trying to design and code my site (far from done XD). And after
    having learned how to make a simple login, I will try to write my own tutorial, for you
    /smile.gif' border='0' style='vertical-align:middle' alt='smile.gif' /> the tutorial Step 1
    : The first step in designing a member system is to plan out exactly what you need. A common impulse
    among programmers is to jump right in and start coding. I'll be honest and admit that I'm
    guilty of this more so than anyone. However, since I'm in control of this conversation (y....
  9. Complete Login System
    With PHP + MYSQL (57)
    Its an complete login sistem made and tested by me and I think itwill be very usefull for people who
    are tryn to learn PHP. First, let's make register.php: CODE <?
    include("conn.php"); // create a file with all the database connections
    if($do_register){ // if the submit button were clicked if((!$name)
    || (!$email) || (!$age) || (!$login) ||
    (!$password) || (!$password2)){ print "You can't let
    any fields in blank....

    1. Looking for simple, php, login, registration, system

*RANDOM STUFF*





*SIMILAR VIDEOS*
Searching Video's for simple, php, login, registration, system

*MORE FROM TRAP17.COM*
advertisement



Simple Php Login And Registration System



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute your information that might help someone here.
Ask your Doubts & Queries to get answers.. "Together, We enlight each other!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE