Password protect pages

Team,

I have created a login page that checks user/pass against a MySQL Database. At the end of this script, you can see where if correct, the user is redirected to valid.html. My concern is that anyone can type in domain/valid.html and get the same page. How do I protect this page where only people who type in correct user / pass can see this page?

[php]<?php

$host = “localhost”;
$username = “timw79_poadmin”;
$password = “xpress13”;
$db_name = “timw79_po”;
$tbl_name=“members”; // Table name

// Connect to server and select databse.
mysql_connect("$host", “$username”, “$password”)or die(“cannot connect”);
mysql_select_db("$db_name")or die(“cannot select DB”);

// username and password sent from form
$myusername=$_POST[‘myusername’];
$mypassword=$_POST[‘mypassword’];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql=“SELECT * FROM $tbl_name WHERE username=’$myusername’ and password=’$mypassword’”;
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file “login_success.php”
session_register(“myusername”);
session_register(“mypassword”);
header(“location:valid.php”);
}
else {
echo "Wrong Username or Password

}
?>[/php]

I’m assuming the user/pass will come from a form?

The proper way to do this is to separate the initial form. it’s just an html page that has submit.php or something similar in the action. then the code that compares the password is it’s own script, separate from the form or the valid.html. then have it ready information to be placed into valid.html which will be a TEMPLATE so that if it is loaded without the script it doesn’t actually do anything.

if you can’t do all that, then your best bet is to use htaccess password protection instead of php, as it’s simpler and protects the file itself.

Sponsor our Newsletter | Privacy Policy | Terms of Service