Jump to content

Recommended Posts

make a login page where the user enters a username and password. query the database to make sure they are valid. start a session with their information, if they are validated. on each page you don't want to be accessed, check if a session has been started. if it has not been started, redirect them to the login page.
okay, so basically you make a form to get the user's name and password:

login.html
[code]
<html>
<head></head>
<body>
<form action = "authenticate.php" method = "post">
     Name:<input name="userename" type="text" size="10"><br>
    Password<input type="password" name="password" size="10"><br>
    <input type="submit" value="login">
</form>
</body>
</html>
[/code]

when the user clicks on the submit button the information will be sent to authenticate.php which looks something like this:

authenticate.php
[code]
<?php
1    session_start();
2    session_register("userinfo");
3    if((!$_POST['username']) or (!$_POST['password']))
4       { header("Location:$HTTP_REFERER"); exit(); }

5    $username=$_POST['username'];
6    $password=$_POST['password'];
          
7    $conn = @mysql_connect("localhost","dbusername","dbpassword") or die("Err:Conn");
8    $rs = @mysql_select_db("dbname",$conn) or die("Err:Db");

9    $sql = "select * from userinfo where name='$userename' and password = '$password' ";
10   $rs = mysql_query($sql, $conn) or die("Err:Query");

11   $match = mysql_numrows($rs);

12   if ($match != 0) {
13      $userinfo=mysql_fetch_array($rs);
14      mysql_close($conn);
15      header("Location:loggedinpage.php");
16      exit();
17   } else {
18         header("Location:loginhelp.php");
19         exit();
20   }
?>
[/code]

so basically this

[b]1[/b] starts a session
[b]2[/b] makes a new session variable called userinfo
[b]3-4[/b] checks to see if user submitted a name and password. if not, then it kicks them back to the page they were just at (which would be login.html)
[b]5-6[/b] assigns some variables to the posted variables. this is optional. i like to do it cuz it's easier to code. less quotes to deal with throughout the code. it's a good idea to do things like strip slashes/tags after this line, but we're shooting for basic.
[b]7-8[/b] connect to the database.
[b]9-10[/b] query the database to see if there is an entry that matches the user's name and password.
[b]11[/b] set a variable to the number of entries that match it. if you coded your registration script properly, there should only be one entry, or none at all, because your registration script should check to make sure the user's name is unique (or whatever info you are checking, like email address)
[b]12[/b] if there is an entry then execute code on lines 13-16
[b]13[/b] assign the user's info from the database to the session variable you created earlier (userinfo)
[b]14[/b] close the database connection
[b]15[/b] redirect the user to whatever page you want them to first see when they are logged in
[b]16[/b] stop parsing any more script in the file.
[b]17[/b] if there was not a match found in the database then run lines 18-20
[b]18-20[/b] redirect user to a login help page or back to the login page or wherever.

okay so, assuming that the user's name and password exist and they are valid you now how their information stored in $userinfo that you can use for the rest of your pages. so the last thing you want to do is, at the beginning of each page that you only want logged in users to be able to go to, you would put this:

[code]
<?php
   session_start();
   if ($userinfo == null) {
      header("Location:loginhelp.php");
      exit;
   }
?>
[/code]

session_start(); starts the session for this page and makes your variable accessible to the page. then the if statement checks to see if your variable exists. It will only exist if the user went through the login page and logged in. if it is null (that is, if it doesn't exist) then it kicks them over to login help or back to login or wherever you want them to go, and stops parsing of anything else on the page.

to access the user's info, all you have to do is for instance, this:

[i]echo "hello there, " . $userinfo['name'] . "!";[/i]

this will echo on the page

[i]hello there, joe![/i]

or whatever the user's name is.

so there you go, a basic login script. this of course assumes that you do have a table setup with user information and you know your database username and password and all that information for authenticate.php to log into the database and check.

also, this is a pretty basic script. it's quick and dirty and gets the job done for the average user but you will want to modify it to make it more secure. for instance, you may want to parse the user's username/password submissions to make sure they are inputting valid things that won't harm your database, etc...

also sql has a built in password encryption thingy that's prety easy to implement. but you would need to alter the query a bit. and/or you may want to do your own md5 encryption of passwords. or whatever.
[!--quoteo(post=370873:date=May 3 2006, 09:08 AM:name=craygo)--][div class=\'quotetop\']QUOTE(craygo @ May 3 2006, 09:08 AM) [snapback]370873[/snapback][/div][div class=\'quotemain\'][!--quotec--]
I got to say Crayon, That is a very good tutorial for this subject. You took some time on that to explain all the details. Hats off my friend. Can't get much clearer than that.

Ray
[/quote]

I agree!
Well done Crayon!!
If you the MySQL Password() you can retrieve it (unencrypt it) if you go the MD5 way you are unable to unencrypt (reverse) it.

So if use choose to MD5 the passwords, and a user forgets what their password was, you will have to generate a new password for them.

Also with MD5, when a user logs in you have to check the MD5 hashs against each other.

So:

[code]
$salt = "ThisIsMySecretMD5Phrase"

// Get input from a form
$password = $_POST['password'];

// Encyrpt the encrypted password & salt
$password = md5(md5($password).md5($salt));

[/code]

Is how I go about encrypting passwords.

So if the user enters [i] deafult123[/i] has a password the encypted version looks like:

[i]092adab8b2d42876ed56bc6b664f1722[/i]

When the user goes to login to the website you have to md5 their password and check it against the hash in the database:

[code]
// Have to use the same salt phrase
$salt = "ThisIsMySecretMD5Phrase"

// User enters their username: test  and password: default123
$username = $_POST['username'];
$password = $_POST['password'];

// Encrypt password that user is trying to login with
$password = md5(md5($password).md5($salt));

// Query the users database
$strqry = "SELECT * FROM users WHERE username = '{$username}' AND password = '{$password}'";
$query = mysql_query($strqry) or die("MySQL Error: <br /> {$strqry} <br />". mysql_error());

// If found - found is set to 1 as long as it doesnt find multiple instances;)
$found = mysql_num_rows($query);
if($found >0) {
  echo "Password/Username matches!";
  //Continue script or move them onto the members section
} else {
  echo "Password or Username do not match those on file.";
  // Have them re-enter the password or....
}
[/code]
valadate the username and password.

If the username or password exist let them choose another.

[code]
if(! $username || $password) {
echo"sorry username tacken!":
<br>
<a href="http://what ever.com>Go Back Try Agin</a>
<br>
exit;
}
[/code]


Also for emails ok

[code]
if(!eregi("^[a-z0-9_]+@[a-z0-9\-]+\.[a-z0-9\-\.]+$",$email)) {
echo"sorry not a valid email address";
<br>
<a href="http://what ever.com>Go Back Try Agin</a>
<br>

exit;
}
[/code]

i Thort i have a go lol all the best.
  • 1 month later...
Hi Crayon,

I have followed all of your directions but am having a problem. When I fill in a bogus login and pass, it sends me to the authenticate.php page and it is blank. Should I see that as a website viewer? I've checked several times and my login and password for the database are correct, so I don't understand why it just stopped on me. Any ideas? I really appreciate your knowledge of this! I am very new to php!!

Thank you!!
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.