Log in

View Full Version : another newbie question - protecting my login



Transentient
10-16-2011, 01:26 PM
Hi all....again

Thanks for all the help so far....learning alot

Following some help from one very helpfull member i managed to get my very simple php login working.

Essentially a form submits data to the code, code compares against a MySQL database.

I have found a little bug, if i copy and paste the url of the protected page into the browser it bypasses the login and goes staright to it. I'm thinking maybe need to use a session which expires either on logout, or after a time delay, or when the browser is closed? Although i'm not sure, my code so far, thanks to JasonDFR, is


<?php
$username = $_POST["username"];
$password = $_POST["password"];
$Login = $_GET["login"];

if($Login == 'yes') {

$con = mysql_connect("mysql19.streamline.net", "homenetne1", "****");

mysql_select_db("homenetne1");

$get = mysql_query("select count(id) FROM Login WHERE user='$username' and pass='$password'");

$result = mysql_result($get, 0);

if($result != 1) {

echo "Invalid Login";

} else {

header( 'Location: http://www.homenet-nexus.co.uk/secure_page.html' ) ;

}

}
?>

Done a little research on sessions, but not sure how to use, and implement within my current code?

Any help, as always will be gratefully accepted

thanks all

fastsol1
10-16-2011, 02:51 PM
There are some great tutorials on youtube for login systems. One of the better ones is from betterphp - http://youtube.com/betterphp

traq
10-16-2011, 04:01 PM
it's not a "bug" - you just need to make sure that the login is checked on every page that needs to be password-protected. The most basic (though not most efficient, nor convenient) way would be to simply include your code above on every page.

A better solution would be to use sessions:

1) on every page, check if the user is logged in by checking a $_SESSION variable (more on this below)

2) if it is not set, redirect to the login page.

3) on the login page, do your username/password check (your code above is fine, except that you need to sanitize the username and password before using them in a DB query - e.g., by using mysql_real_escape_string() - your current code is wide open to injection!)

4) if the login is successful, set a session variable (e.g., $_SESSION['logged_in'] = TRUE) that you can check on subsequent pages (see step 1).