Jump to content


Photo

Login/Register PHP Script


  • Please log in to reply
11 replies to this topic

#1 treilad

treilad
  • Members
  • PipPipPip
  • Advanced Member
  • 58 posts

Posted 14 July 2006 - 12:33 AM

I'm trying to get a site up and running with a few buddies of mine who don't know anything about coding/programming, so they're not much help. I know HTML and basic CSS. I just recently started a few PHP tutorials and have been working night and day to become fluent. I downloaded WAMP5 so I could learn some database management and such. I can get PHP scripts to access my database(s), but I'm having some trouble trying to get the login/register aspect of my website to work. I'm ashamed to say that I merely copied the code off of another tutorial site, which I know is a no-no. Needless to say, it's a bit out of my league. I'm not to the point where I can really go through and pick out errors yet, and this is the first time I've dealt with code this complicated.

The following is my registration.php code. My name and password have been withheld to protect the innocent.  :-\

<?php
// Connects to your Database
mysql_connect("host", "user", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());

//This code runs if the form has been submitted
if (isset($_POST['submit'])) {

//This makes sure they did not leave any fields blank
if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] ) {
die('You did not complete all of the required fields');
}

// checks if the username is in use
if (!get_magic_quotes_gpc()) {
$_POST['username'] = addslashes($_POST['username']);
}
$usercheck = $_POST['username'];
$check = mysql_query("SELECT username FROM users WHERE username = '$usercheck'")
or die(mysql_error());
$check2 = mysql_num_rows($check);

//if the name exists it gives an error
if ($check2 != 0) {
die('Sorry, the username '.$_POST['username'].' is already in use.');
}

// this makes sure both passwords entered match
if ($_POST['pass'] != $_POST['pass2']) {
die('Your passwords did not match. ');
}

// here we encrypt the password and add slashes if needed
$_POST['pass'] = md5($_POST['pass']);
if (!get_magic_quotes_gpc()) {
$_POST['pass'] = addslashes($_POST['pass']);
$_POST['username'] = addslashes($_POST['username']);
}

// now we insert it into the database
$insert = "INSERT INTO users (username, password)
VALUES ('".$_POST['username']."', '".$_POST['pass']."')";
$add_member = mysql_query($insert);
?>

<!-- Now we let them know if their registration was successful -->
<h1>Registered</h1>
<p>Thank you, you have registered - you may now login</a>.</p>
<?php
}
else
{
?>

<!-- This is what they see before they have registered -->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="0">
<tr><td>Username:</td><td>
<input type="text" name="username" maxlength="60">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="pass" maxlength="10">
</td></tr>
<tr><td>Confirm Password:</td><td>
<input type="password" name="pass2" maxlength="10">
</td></tr>
<tr><th colspan=2><input type="submit" name="submit" value="Register"></th></tr> </table>
</form>

<?php
}
?>


Now my login.php code.

<?php

// Connects to your Database
mysql_connect("host", "user", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());


//Checks if there is a login cookie

if(isset($_COOKIE['ID_my_site']))


//if there is, it logs you in and directes you to the members page
{
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];

$check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error());

while($info = mysql_fetch_array( $check ))
{

if ($pass != $info['password'])
{

}

else
{
header("Location: members.php");

}

}

}


//if the login form is submitted

if (isset($_POST['submit'])) { // if form has been submitted


// makes sure they filled it in

if(!$_POST['username'] | !$_POST['pass']) {
die('You did not fill in a required field.');
}

// checks it against the database

if (!get_magic_quotes_gpc()) {
$_POST['email'] = addslashes($_POST['email']);
}

$check = mysql_query("SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error());

//Gives error if user dosen't exist

$check2 = mysql_num_rows($check);
if ($check2 == 0) {
die('That user does not exist in our database. <a href=add.php>Click Here to Register</a>');
}


while($info = mysql_fetch_array( $check ))
{

$_POST['pass'] = stripslashes($_POST['pass']);
$info['password'] = stripslashes($info['password']);
$_POST['pass'] = md5($_POST['pass']);

//gives error if the password is wrong

if ($_POST['pass'] != $info['password']) {
die('Incorrect password, please try again.');
}

else
{
// if login is ok then we add a cookie

$_POST['username'] = stripslashes($_POST['username']);


$hour = time() + 3600;
setcookie(ID_my_site, $_POST['username'], $hour);
setcookie(Key_my_site, $_POST['pass'], $hour);

//then redirect them to the members area
header("Location: members.php");
}

}

} else {

// if they are not logged in
?>

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Login</h1></td></tr>
<tr><td>Username:</td><td>
<input type="text" name="username" maxlength="40">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="pass" maxlength="50">
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Login">
</td></tr>
</table>
</form>
<?php
}


?>


And my members.php code.

<?php
// Connects to your Database
mysql_connect("host", "user", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());

//checks cookies to make sure they are logged in
if(isset($_COOKIE['ID_my_site']))
{
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error());
while($info = mysql_fetch_array( $check ))
{

//if the cookie has the wrong password, they are taken to the login page
if ($pass != $info['password'])
{ header("Location: login.php");
}

//otherwise they are shown the admin area
else
{
echo "Admin Area<p>";
echo "Your Content<p>";
echo "<a href=logout.php>Logout</a>";
}
}
}
else

//if the cookie does not exist, they are taken to the login screen
{
header("Location: login.php");
}
?>

The notes are still in from the tutorial site.

I have the code for registration.php copied within a table on my website. The only thing it says when I go there is "Thank you for registering. You may now login." And that's before I register, so I know it's not supposed to do that. On the login page, the shows the login form, but half of the php code is visible on the page and I don't know why.

One more thing. I know I can't leave the actual PHP code in the page code because it would pose some obvious security problems. I'd like to know how to reference the php file from the page code so the php file isn't online for everyone to see.

I'm relatively new to PHP so I don't know of any safety precautions I should take when setting up a login system, be it making sure nobody can see my php code and securing my databases or otherwise. Any advice in that area would be very much appreciated. Thanks a ton.

-Matt

#2 lordphate

lordphate
  • Members
  • PipPipPip
  • Advanced Member
  • 154 posts

Posted 14 July 2006 - 12:53 AM

It's wierd because everything works for me :|

#3 treilad

treilad
  • Members
  • PipPipPip
  • Advanced Member
  • 58 posts

Posted 14 July 2006 - 12:56 AM

I think it may be due to the fact that I have the scripts typed out in html within a table, and I know very little about getting PHP and HTML to cooperate. My question about how to not type in the actual code in the HTML and just reference it to a PHP file might help.

#4 lordphate

lordphate
  • Members
  • PipPipPip
  • Advanced Member
  • 154 posts

Posted 14 July 2006 - 12:57 AM

Except when you try to login and yur not a member, you need to change the

$check2 = mysql_num_rows($check);
if ($check2 == 0) {
      die('That user does not exist in our database. <a href=add.php>Click Here to Register[/url]');
            }

to
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
      die('That user does not exist in our database. <a href=register.php>Click Here to Register');
            }


#5 lordphate

lordphate
  • Members
  • PipPipPip
  • Advanced Member
  • 154 posts

Posted 14 July 2006 - 12:58 AM

What i suggest is to create SEPERATE files for HTML and PHP...just include the html file in the php by include()

#6 treilad

treilad
  • Members
  • PipPipPip
  • Advanced Member
  • 58 posts

Posted 14 July 2006 - 01:02 AM

Sorry.  :-\ That doesn't mean a lot to me. Could you go a little more step-by-step?

#7 lordphate

lordphate
  • Members
  • PipPipPip
  • Advanced Member
  • 154 posts

Posted 14 July 2006 - 01:07 AM

Look at the tutorials here on phpfreaks...actually...hold on...I'll let you copy some of my coding...This is login.php ....
<?php
include ('header.php');
include ('sidebar.php');
include 'rightbar.php';  

echo ('
<form action="login2.php" method="post">
<table width="98%" border="0" cellspacing="1" cellpadding="1">
<tr>
<td>UserName:</td>
<td><input name="name" type="text" id="name" maxlength="30"></td>
</tr>
<tr>
 <td>PassWord:</td>
<td><input name="password" type="password" id="password" maxlength="10"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="login"></td>
</tr>
</table>
</form>  '); include ('footer.php'); ?>
This is login2.php
<?php
             include ('./library/db.php');
// For register_global on PHP settings
$name = $_POST['name'];
$password = $_POST['password'];
// Check for empty fields
if (empty($name) || empty($password))
{
die ("Error. Please fill in all required fields."); // once a die statement is execute, the whole script stops executing
}

// Match Row in Database
$qChk = "select name from membership where name='$name' and password='$password' and status='Y' ";
$rsChk = mysql_query($qChk);

$rowCount = mysql_num_rows($rsChk);

if ($rowCount !='1') // query did not return 1 row, user is not verified
{
die ("Error. Your password does not match your username or your account was not yet activated. Please try again.");
}

// User is login. Let's give him a cookie. *Munch*
setcookie ("member",$name,time()+1957240,"/");
$member = $name;
session_register("member"); // set session, just in case cookie is blocked.

// Update Login timer
$qUpdate = "update membership set login = now() where name='$name' and password='$password' and status='Y' ";
$rsUpdate = mysql_query($qUpdate);

if ($rsUpdate)
{
header("Location: index.php"); // redirects members to a welcome member page
}

?>


#8 fert

fert
  • Members
  • PipPipPip
  • Advanced Member
  • 1,114 posts

Posted 14 July 2006 - 01:37 AM

I'm trying to get a site up and running with a few buddies of mine who don't know anything about coding/programming, so they're not much help. I know HTML and basic CSS. I just recently started a few PHP tutorials and have been working night and day to become fluent. I downloaded WAMP5 so I could learn some database management and such. I can get PHP scripts to access my database(s), but I'm having some trouble trying to get the login/register aspect of my website to work. I'm ashamed to say that I merely copied the code off of another tutorial site, which I know is a no-no. Needless to say, it's a bit out of my league. I'm not to the point where I can really go through and pick out errors yet, and this is the first time I've dealt with code this complicated.

The following is my registration.php code. My name and password have been withheld to protect the innocent.  :-\

<?php
// Connects to your Database
mysql_connect("host", "user", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());

use
$connection=@mysql_connect("host","user","password");

Si hoc legere scis nimium eruditionis habes
Gentoo Linux 2007.0 Firefox 2

#9 treilad

treilad
  • Members
  • PipPipPip
  • Advanced Member
  • 58 posts

Posted 14 July 2006 - 01:43 AM

Thanks a ton. I'll try both of those and see what I can do. I'll probably be back, though.  ???

#10 pixy

pixy
  • Members
  • PipPipPip
  • Advanced Member
  • 295 posts

Posted 14 July 2006 - 02:38 AM

use
$connection=@mysql_connect("host","user","password");

But if you use the @ it suppresses errors, which is not something you want. You need to see the errors to be able to fix them.

try this:
$connection = mysql_connect("host", "user", "password") or die(mysql_error());

That way it'll tell you WHY the connection failed.

This is a .44 Caliber Loveletter straight through my heart.

Tabulas + Threadless + Hire Me!


#11 treilad

treilad
  • Members
  • PipPipPip
  • Advanced Member
  • 58 posts

Posted 14 July 2006 - 03:24 AM

Thanks Pixy. :)

#12 treilad

treilad
  • Members
  • PipPipPip
  • Advanced Member
  • 58 posts

Posted 14 July 2006 - 01:37 PM

But then where would I include 'mysql_select_db("database") or die(mysql_error());'?




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users