Jump to content

Login/Register PHP Script


treilad

Recommended Posts

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
Link to comment
Share on other sites

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.
Link to comment
Share on other sites

Except when you try to login and yur not a member, you need to change the [quote]$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]');
            }[/quote] to [code]$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');
            }[/code]
Link to comment
Share on other sites

Look at the tutorials here on phpfreaks...actually...hold on...I'll let you copy some of my coding...This is login.php ....
[code]<?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'); ?>
[/code] This is login2.php [code]<?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
}

?>
[/code]
Link to comment
Share on other sites

[quote author=treilad link=topic=100512.msg396737#msg396737 date=1152837230]
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());

[/quote]
use
$connection=@mysql_connect("host","user","password");
Link to comment
Share on other sites

[quote author=fert link=topic=100512.msg396759#msg396759 date=1152841071]
use
$connection=@mysql_connect("host","user","password");
[/quote]
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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

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.