NameSilo

A little better login script (with MySQL) - And page protection with session controls

NamecheapNamecheap
Watch
Impact
111
Hi,

Actually, I hope this isn't in the wrong forum, since it's been done before I'm sure, but just a little enhancement to SecondVersion's post a bit downward...

Now, I actually send an HTTP re-direct in case a certain nav panel on the side or top of the page needs to be updated upon a login. Because sessions and cookie variables don't take effect or are recognized until the page AFTER login, an HTTP redirect is used to keep things current without having to check filenames :| This is entirely optional but I think it works better and I recommend it.

Note: For the re-direct, PHP function header() can be used:

PHP:
header ('Location: page.php');

before any other headers are sent and that will redirect before the page displays any content (if there IS any to be displayed) - the page won't even be sent to the browser (which is WHY headers have to go before stuff sent to the browser) until that header tag to redirect it.

This SHOULD really work (haven't tried it) but I scanned the code for errors. Please note! This is NOT a very secure script! (I've written better...)

index.html (login page)
HTML:
<html>
<head>
<title>Login</title>
</head>
<body>

<form method="post" action="login.php">
Username: <input type="text" name="username">
<BR><BR>
Password: <input type="password" name="password">
<BR><BR>
<input type="submit" value="Login">
</form>

</body>
</html>

Now, when the user presses the "Login" button, it goes to the action:

login.php
PHP:
<?php

//Start up the session for when we set the session variables!

session_start();

/*
Assign these a value - I'm pretty sure this prevents the variables being sent via GET in the URL.

I'm also gonna shorten the variable names to make them easier to work with.
*/

$uname = $_POST['username'];
$pwd = $_POST['password'];

//Now, check to see if the user filled out both fields.

if (empty($uname) || empty($pwd))
{
    echo 'You must fill out both the username and password.';
    exit;
}

/*
Now, encrypt the $pwd variable (assuming and HOPEFULLY) since you encrypted them in the MySQL database. I prefer md5. It's ALWAYS 32 characters long.
*/

$pwd = md5($pwd);

//connect...
mysql_connect('localhost', 'db_username', 'db_password');
mysql_select_db('db_name');

//Run the query...
$query = "SELECT * FROM users WHERE username='$uname' AND password='$pwd' LIMIT 1";

$result = mysql_query($query);

//How many results...?
$num = mysql_num_rows($result);


//No results... meaning they didn't match...
if ($num < 0)
{
    echo 'That is an invalid username/password combo. Please try again.';
    exit;
}

//now... if they DID match, set the session variables and display a successful login.

//For this example, I'm just storing username - but in more advanced sites,
//you will want to store more and check them every protected page
//to make sure they are valid and it will be more secure.

if ($num == 1)
{
    $_SESSION['username'] = $username;

//Done with the PHP! Display the success and redirect.
?>
<html>
<head>
<meta http-equiv="REFRESH" content="0; url=protected_page.php">
<title>Login successful!</title>
</head>
<body>
Login successful... please wait until you are redirected...
</body>
</html>
<?php
//Close the IF block
}
?>

Now, this script will store the username in a session variable and redirect to "protected_page.php".

The script for that is as follows:

protected_page.php
PHP:
<?php

//Start the session! Always do this FIRST when working with sessions!
session_start();

//Does the session variable we set earlier exist?
if (!isset($_SESSION['username']))
{
     echo 'You have to be logged in to see this page!';
     exit;
}

//Now, if the script came this far, the user is authenticated and can see the page.

?>
<html>
<head>
<title>Secret Page</title>
</head>
<body>
<p>Here is the secret page!</p>

<p>I bet you are glad you get to see this secret page.</p>

<p>Woopdie-doo...</p>
</body>
</html>

Hope it works... lol... it should ;)

EDIT! Guess I should tell ya how to log out.

It's really easy!

logout.php
PHP:
<?php

//Start the session, of course. Actually maybe it's ironic,
//since what we want to do is logout. But just start the
//session for now. lol...
session_start();

//Destroy the session variable we set earlier.

unset($_SESSION['username']);

//Destroy the session entirely now.

session_destroy();

//Done!

?>
<html>
<head>
<title>Logged out!</title>
</head>
<body>
You have been logged out. Session destroyed.
</body>
</html>
 
Last edited:
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
GoDaddyGoDaddy
:hehe:
 
0
•••
if you didnt know session_start(); and then space and comments above it, isnt allowed. it will give you header problems.
 
0
•••
Actually, it just has to be sent before any other headers ;) It works fine ;)
 
0
•••
xlusive said:
if you didnt know session_start(); and then space and comments above it, isnt allowed. it will give you header problems.

you are allowed to put anything before session_start(); as long as it doesnt get passed to the browser for rendering. only then you will get header problems.
 
0
•••
You might want to add re-authentication and IP checking in the script also. Added security and the IP check helps with preventing session Hijacking...
 
0
•••
Good job, if I didn't write my own code and still stole others, I would probs steal it :P

PJ
 
0
•••
No no - use it if you want! Share it with the WORLD... that took me 5 mins to write anyway...

I updated the script and added a logout function!
 
0
•••
Cool and standard. Good work.
 
0
•••
0
•••
Dynadot โ€” .com TransferDynadot โ€” .com Transfer
Appraise.net
Spaceship
Domain Recover
CatchDoms
DomainEasy โ€” Live Options
  • The sidebar remains visible by scrolling at a speed relative to the pageโ€™s height.
Back