My membership script is working except this one file. When I type username and password in the login form the check.php gives me this message "Please enter all information". The only information on the login form is username and password. The action of the login form is posted on check.php
I need this script to check the username and md5 encrypted password in my database and redirect to member area. I'm using random passwords. This is the only problem. Here is the check.php script. Please let me know what I need to do for this to work. I got this script from someone else and they don't know how to fix it either. I don't know php. Just want to copy and paste. Thanks
============================
<?
/* Check Username Script */
session_start(); // Start Session
include 'database.php';
// Conver to simple variables
$username = $_POST['username'];
$password = $_POST['password'];
if((!$username) || (!$password)){
echo "Please enter ALL of the information! <br />";
include 'login_form.html';
exit();
}
// Convert password to md5 hash
$password = md5($password);
// check if the user info validates the db
$sql = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' AND activated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_array($sql)){
foreach( $row AS $key => $val ){
$$key = stripslashes( $val );
}
// Register some session variables!
session_register('first_name');
$_SESSION['first_name'] = $first_name;
session_register('last_name');
$_SESSION['last_name'] = $last_name;
session_register('email_address');
$_SESSION['email_address'] = $email_address;
session_register('special_user');
$_SESSION['user_level'] = $user_level;
mysql_query("UPDATE users SET last_login=now() WHERE userid='$userid'");
header("Location: members.php");
}
} else {
echo "You could not be logged in! Either the username and password do not match or you have not validated your membership!<br />
Please try again!<br />";
include 'login_form.html';
}
?>
This is the only part of the script that I could copy here. I'm using sessions. Action is POST.
It sounds like a typo, either when you set the $username $password variables, or in your form. Check that name is correct on the form inputs :)
also, it is better to use isset($username) instead of !$username. Doesn't give a warning :)
In your form, make sure the input fields that ask for the username and password have the correct name associated with it.
For example:
<input type='text' name='username'>
<input type='password' name='password'>
The value after name= is what gets passed as the variable name. To demonstrate that, the input field:
<input type='text' name='thisIsMyName'>
will show up in the PHP script as:
$_POST['thisIsMyName'];
If you post the HTML of the form that is being submitted, we can give you further details on it.
please post the content of login_form.html. I guess that this form is either using GET instead of POST or the input fields are not named "username" and "password".
Something else: This code contains a very serious security issue:
$username = $_POST['username']
mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' AND activated='1'");
This means that an attacker can manipulate the sql statement. For example the username:
admin'--
will result in this sql query:
SELECT * FROM users WHERE username='admin'--' AND password='egal' AND activated='1'
which means:
SELECT * FROM users WHERE username='admin'
And will grant access if a user named "admin" exists, ignoring the password.
Note: Filtering for -- will not help as there are number of other ways to have fun with this. You need to mysql_real_escape_string($username) to escape special characters in the input. More information is available at http://php.net/manual/en/function.mysql-real-escape-string.php
Related
I'm trying to get a login page to work with PHP and Mysql. I've combed through my code, and don't know where I'm going wrong.
First I have a "login.php" page. Here's (what I believe) is the important code on that page:
<form id="login" action="redirect.php" method="post"> <!--This is the form for logging in.-->
<fieldset id="inputs">
<input type="hidden" name="ac" value="log"> <!--This value is a "random" value to post so that an if statement will be entered in select.php-->
<input id="username" name="username" type="text" placeholder="Username" autofocus required>
<input id="password" name="password" type="password" placeholder="Password" required>
</fieldset>
<fieldset id="actions">
<input type="submit" id="submit" value="Log in">
</fieldset>
From there you'll see that when submit is pressed it goes to "redirect.php" which has the following code:
<?php
include 'config.php';
$username = $_POST['username'];
$password = $_POST['password'];
function SignIn()
{
session_start(); //starting the session for user profile page
if(!empty($username)) //check to see if the username is empty or not from login.php
{
$query = mysqli_query($con, "SELECT * FROM employees where username = ".$username." AND password = ".$password) or die(mysql_error());
$row = mysqli_fetch_array($query) or die(mysql_error());
if(!empty($row['username']) AND !empty($row['password']))
{
$_SESSION['username'] = $row['password'];
echo "SUCCESSFULLY LOGGED IN!";
}
else
{
echo "YOU ENTERED WRONG ID OR PASSWORD...";
}
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>
You'll notice the config.php page is included... Here's the code for that (with my dbusername and dbpassword changed:
<?php
/* Database credentials. */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'myusername');
define('DB_PASSWORD', 'mypassword');
define('DB_NAME', 'ropepart_techportal');
/* Attempt to connect to MySQL database */
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($con === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
When I run through all of this on my webpage, I am greeted with a blank white page on the redirect.php. This is the case no matter what username/password combo I put in the login.php page. Whether or not the user actually exists in the database or not. I would expect to get at least a sentence at the top of the page that either says "SUCCESSFULLY LOGGED IN!" or "YOU ENTERED WRONG ID OR PASSWORD." Any idea where I'm going wrong?
You're not sending value for submit in post body.
Try adding :
<input type="submit" name="submit" id="submit" value="Log in">
Since you've checked isset($_POST['submit']) which since you're not sending evaluates to false , and SignIn() is never called
I agree with our friend here, you set id for input, but you need set name to be send during the request, but I strong recomend u change two things in your code
add this attr to input submit -> name="submit"
Instead of this
if(isset($_POST['submit']))
{
SignIn();
}
Use this
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
SignIn();
}
And don't do this on start of the code
$username = $_POST['username'];
$password = $_POST['password'];
Because when u try to access an array that is not defined the php can outputs an error, and for some security reasons this isn't recommend, so before set the variables, check it, like this:
if (isset($_POST['username']) {
$username = $_POST['username'];
}
Your intimidate problem is there is no scope resolution on your variables
$username = $_POST['username'];
$password = $_POST['password'];
function SignIn(){
//$username does not exist in this scope
Instead
function SignIn($username, $passwrd){
....
}
SignIn($username, $passwrd);
That said their is a bunch of other "stuff" that I would fix, give me a few minutes and I will post something on it. Now if you had error reporting on you would see something like this
Warning: undefined variable $username
Here you go (untested but it should be close)
<?php
//turn on error reporting for development
//note even this may not catch syntax errors if they happen in this file
error_reporting(-1);
ini_set('display_errors',1);
require_once 'config.php'; //should be require once for a config
session_start(); //starting the session for user profile page
$dashboard = 'http://localhost/dashboard'; //some location to send a user after login
if(!empty($_SESSION['username'])){
//user is already logged in
header('Location: '.$dashboard);
}
//array for error tracking
$errors = [];
//if(isset($_POST['submit']))
//by checking the below outside of this we are assuming post
// has already happend, so there is no need to check this
//it was similar in your original code.
//if post isn't set then username and password will be FALSE
//and it will be caught by the error checking for those anyway
$username = isset($_POST['username']) $_POST['username'] : false; //check if isset if not set a default
if(!$username) $errors[] = 'Please enter a username';
$password = isset($_POST['password']) $_POST['password'] : false;
if(!$password) $errors[] = 'Please enter a password';
if(count($errors)){
//return to the page with error messages
//I have no idea how you build the page or how it relates to this
//so I cant hellp you there
die(implode('<br>', $errors));
}else{
//use single quotes for SQL, which prevents accidentally putting a variable in it.
// '$password' is literally $password, but "$password" is the value of it
//look up only what you need (password)
//don't look up by the password, DB is case insensitive and
//and is not cryptologicalally secure way to compare hashes.
$stmt = mysqli_prepare($con, 'SELECT password FROM employees where username = ?');
//I don't use mysqli (for like 4 years, and I never used the procedural style)
//so I had to look this up, if it's not right sorry ;-/, this is so much harder then PDO
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $user);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $hash);
//not sure this will work, sorry
//in the example it showed storing the results,
//so not sure if you have to do that.
$num_rows = mysqli_stmt_num_rows($stmt);
//check that one and only one row is returned
if(!$num_rows){
//User not found, again I have no idea how to display this for you
die('Username was incorrect, please try again.');
}else if($num_rows > 1){
//should never happen with unique usernames
// again I have no idea how to display this for you
//this can prevent some errors from allowing logins
//this is an error message you may not want to show in production code
die('Returned more then one user account.');
}
/* fetch value */
//because we did mysqli_stmt_bind_result($stmt, $hash)
//which is bind $hash to column 1, this populates that
//variable with the data from the first row
mysqli_stmt_fetch($stmt);
//bool password_verify ( string $password , string $hash )
//Aug1 $password is plaintext, Arg2 $hash is from the DB
if(password_verfy($password, $hash)){
$_SESSION['username'] = $row['username'];
//you had password here in your original code (another bug?)
//$_SESSION['username'] = $row['password'];
//user is already logged in
header('Location: '.$dashboard);
}else{
//Incorrect password, again I have no idea how to display this for you
die('Your password was incorrect, please try again.');
}
}
I ditched the function call, as you mentioned in the comments.
I decided to get rid of my SignIn() function entirely, as it seems to not be needed in this case
You can read about prepared statements here
http://php.net/manual/en/mysqli.prepare.php
As I mentioned in the code, I haven't used mysqli much in the last 4 years, and even then I never used the procedural style. I quit doing the procedural style when I switched from mysql to mysqli about 7 years ago. There may be better ways to do that in mysqli, I just copied the example on the PHP documentation site. With PDO it would just be this (which is so much more elegant):
$stmt = $PDO->prepare('SELECT * FROM employees where username = :username');
$stmt->execute([':username' => $username]);
$num_rows = $stmt->rowCount();
$pass = $stmt->fetchColumn(0);
And the above assumes you are using PHP's built in password functions, which you should.
So to create a password use password_hash.
http://php.net/manual/en/function.password-hash.php
And to check it use password_verfy.
http://php.net/manual/en/function.password-verify.php
SQL Injection
In your original code we could turn you query into this,
"SELECT * FROM employees where username = ".$_POST['username']." AND password = ".$_POST[password]"
This is equivalent to what you have. Without preparing it someone can enter " OR 1=1 in the password field. There are only 2 styles of quotes and it wouldn't take much to figure it out. You can also encode the quotes in some instances, so simply checking for quotes wont due. What this would do is make your query:
SELECT * FROM employees where username = "admin" AND password = "" OR 1=1
Now because 1 is always equal to one 1 and this is password OR 1 then it effectively bypasses the password. You should only pull the password from the DB and then check it in PHP. That would prevent all of this (even with the sql issues) because as an attacker I would still need the password to pass that check. For example.
SELECT password FROM employees where username = "" OR 1=1
...
//even with a hacked row from the DB I still don't have $_POST['password']
if($_POST['password'] == $row['password'])
A few other Attacks
For the username it's almost the same " OR 1=1 --. The -- is the start of a line comment in SQL. And, because you are not checking the number of returned results it would also log me in as probably the first user found.
SELECT * FROM employees where username = "" OR 1=1 -- AND password = "
However if even if you did (check the number of results) all I would need to add is LIMIT 1 " OR 1=1 LIMIT 1 -- to it. I would probably do it this way anyway, if I was a hacker.
SELECT * FROM employees where username = "" OR 1=1 LIMIT 1 -- AND password = "
Then to boot I could iterate thought all your users by using an offset.
SELECT * FROM employees where username = "" OR 1=1 LIMIT 0, 1 -- AND password = "
SELECT * FROM employees where username = "" OR 1=1 LIMIT 1, 1 -- AND password = "
SELECT * FROM employees where username = "" OR 1=1 LIMIT 2, 1 -- AND password = "
etc.
And then steal all their stuff, or pick one with administrative rights your site etc.
Problem with not encrypting passwords
One of the biggest problems (outside of the obvious ones) is that users are lazy and they tend to use the same passwords. So once I compromised and admin account or even if you show the old password when a user goes to change it. Whatever way I get it... I could try that password against their email, also in their account. And once I find the poor sucker that has the same email password, I could find any sites they use. Then use that common password (preferred as they wont even know) or now that I own their email account I can just reset the password if I need to, to gain access to things like their online banking accounts etc..
So as you can see this is not something we can allow to happen.
Even when just learning, we should try to learn to do it the proper way, or at least in a way that offers some minimal security.
Cheers.
I have this user login process page. at this point the user has entered the info and all of this works BUT I cannot figure out how to pull the encrypted password out of the DB. I need to extract with the PASSWORD() function and do not know how. I know this is not the best way to do it but its what the assignment calls for. I have the problem section commented out I think thats what needs fixing.
//sets $query to read usnername and passowd from table
$query = "SELECT username,password,first_name,last_name FROM jubreyLogin WHERE username
= '$userName' AND password=password('$userPassword')";
$result = mysql_query($query,$db);
if(mysql_error())
{
echo $query;
echo mysql_error();
}
//reads data from table sets as an array
//checks to see if user is already registered
while($row=mysql_fetch_array($result))
{
if($userName == $row['username'] /*&& $userPassword == ($row['password'])*/)
{
$login = 'Y';
$welcome = "Welcome" . " " .$row['first_name']. " " .$row['last_name'];
$userName = $row['username'];
}
}
if ($login='Y')
{
setcookie('name',$welcome,time()+60*60*24*30);
setcookie('login',"Y",time()+60*60*24*30);
$_SESSION['username_login'] = $userName;
header('Location: welcome.php');
}
Here is the modified code that I should of posted first I need it to check user entered password in this case $userPassword with the encrypted password if its a match it will send the user into the next page of the site.
You don't need to see the password in clear text ( you can't even if you wanted to). As you are checking the record both on password and username you don't need the check in your if() statement. If there is any row found, that means the username/password combination was succesfful and the user can be deemed as logged in.
Edit:
The updated code doesn't really make any difference to the actual logic. The logic stays the same, you query the database with username AND encrypted password, if there is a match that means the user has the right to login, so you proceed with setting the cookies/session data and redirect. Although I do not really see the need for the login cookie and the welcome cookie cause you could simply put in both username, fname and lname in the session. If the session on the following pages contains username that means the user has logged in.
The code can go something like this:
//sets $query to read usnername and passowd from table
$query = "SELECT username,first_name,last_name FROM jubreyLogin WHERE username = '$userName' AND password=password('$userPassword')";
$result = mysql_query($query,$db);
if(mysql_error())
{
echo $query;
echo mysql_error();
}
// were any rows returned?
if(mysql_num_rows($result)){
list($userName, $firstName , $lastName) = mysql_fetch_row($result);
$welcome = "Welcome" . " " .$firstName. " " .$lastName;
setcookie('name',$welcome,time()+60*60*24*30);
setcookie('login',"Y",time()+60*60*24*30);
$_SESSION['username_login'] = $userName;
header('Location: welcome.php');
}
You should not be encrypting your passwords, you should be hashing them. Try using a library such as phpass to be on the safe side. What you will need to do is hash the passwords and store the hashed value in the database. When a user logs in, you will hash the password they provide and compare that with the hashed value in the database. If the hashes match, the password provided is correct. If not, you send an error to the user. You never need to be able to obtain the password in plain text in order to validate a user.
Also, make sure that you are either escaping your variables using mysql_real_escape_string() or prepared statements or your script will be vulnerable to SQL injection.
Well, I am working on a new project which has a login page. The Error: I am unable to retrieve password from the form using $_POST method.
The Form Code:
<form action="loginsub.php" method="post">
<input type="password" name="pass" id="pass"/><br/>
<input type="submit" value="Go!"/>
</form>
The Code in loginsub.php
<? echo $_POST['pass']; ?>
I have also tried this method using text in place of password and it works. But what is the problem with the password? When I fill in the form and then submit it, the next page displays nothing!
Okay, Now, It's working! Thank you all, The Real Problem was: I want to take in password from a login form and then using mysql_query (php) want to find out if the username and password combination is there or not. If I am not wrong, the code for it is:
require_once('dbconfig.php');
$username = $_POST['username'];
$pass = $_POST['pass'];
$dbc = mysql_connect($dbserver,$dbuser,$dbpassword);
mysql_select_db('hello');
$query = "SELECT * FROM users WHERE username = '$username' AND password = PASSWORD('$pass')";
$result = mysql_query($query);
$row = mysql_num_rows($result);
if ($row == 1)
{ echo "User Name and Password are Correct"; }
else
{ echo "Error! Username and Password is Wrong!"; }
Is the code right? When I execute it, enter correct username and password (which exists in the database, I get the InCorrect Message, but again when I enter wrong username and password, I still get InCorrect message. Why?
I take you don't really want to print the password in your application? Anyway, it should be in your $_POST array - could you paste the output of putting
var_dump( $_POST );
in the page your submitting to?
How can I ensure my login script is secure and make it better, This is my first code:
Help is most appreciated.
<?php
include ('../includes/db_connect.php');
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$username = $_POST['username'];
$password = md5($_POST['password']);
// lets check to see if the username already exists
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
$username_exist = mysql_num_rows($checkuser);
if($username_exist > 0){
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
header("Location: /registration?registration=false");
exit();
}
// lf no errors present with the username
// use a query to insert the data into the database.
$query = "INSERT INTO users (firstname, lastname, email, mobile, username, password)
VALUES('$firstname', '$lastname','$email', '$mobile','$username', '$password')";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "You have successfully Registered";
header("Location: /registration?registration=true");
// mail user their information
//$yoursite = ‘www.blahblah.com’;
//$webmaster = ‘yourname’;
//$youremail = ‘youremail’;
//
//$subject = "You have successfully registered at $yoursite...";
//$message = "Dear $firstname, you are now registered at our web site.
// To login, simply go to our web page and enter in the following details in the login form:
// Username: $username
// Password: $password
//
// Please print this information out and store it for future reference.
//
// Thanks,
// $webmaster";
//
//mail($email, $subject, $message, "From: $yoursite <$youremail>\nX-Mailer:PHP/" . phpversion());
//
//echo "Your information has been mailed to your email address.";
?>
Follow Artefacto's advice about SQL injection and Hashing passwords in the database. Other things ...
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
header("Location: /registration?registration=false");
Wont work because you can't echo then send a header. Headers must be sent before any output.
Also, there is no point doing this:
header("Location: /registration?registration=false");
echo "I'm sorry but the username you specified has already been taken. Please pick another one.";
unset($username);
The webbrowser will redirect straight away and the user won't see the handy message you've printed.
Also, it's usual to ask for 2 password fields on registration forms incase the user made a typo and didn't notice because all the text was *'s. You compare the 2 and if they are different you assume a typo was made and ask again.
That's not a login script. It's a registration script.
See SQL injection in the PHP manual. Your program is vulnerable to this kind of attacks.
Also, don't just or die(mysql_error()). This will expose information about your database that you may not want to expose (table names, etc.). Use proper error handling. For instance, you can throw an exception and define a uncaught exception handler that shows a "oops" page and logs the error.
Finally, use hashes strong than MD5, such as sha1.
As said by #Artefacto, that's not a login script.
But if you intend to do a login script I would like to give you a suggestion. I've done this a while ago.
Instead of doing something like this:
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
I would do this:
$sql = "SELECT * FROM users WHERE username = '$username'";
$user = //use the php-sql (query, fetch_row) commands to fetch the user row.
if (strcmp($user['password'], $password) == 0) {
//log in success
}
By doing this, you avoid SQL Injection in a simple and elegant way. What you guys think about it?
To reiterate what everyone else mentioned. It's important to protect yourself (and sever) from SQL injection. For example:
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
You're just simple taking the value from $_POST['username'] and placing it in the variable $username.
Some people aren't very nice and will try to break your program :( So it's always recommended to escape any data that was taken from a user, before placing it into an SQL query.
For instance...
This:
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
Becomes:
$checkuser = mysql_query("SELECT username FROM users WHERE username='" .mysql_real_escape_string($username). "'");
So recently I learned how to properly add a username and password to a database.
My database is usersys, and the table storing user information is called userdb. The table has two columns - username (primary), password.
The registration form works great, enters the users input into the database correctly and also checks to see whether the user's username is already in the database or not.
With that said, I am asking if anyone could help me create a login script. So far, this is what I have:
$username = $_POST['username'];
$password = $_POST['password'];
$displayname = $_POST['username'];
$displayname = strtolower($displayname);
$displayname = ucfirst($displayname);
echo "Your username: " . $displayname . "<br />";
mysql_connect("localhost", "root", "******") or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("usersys") or die(mysql_error());
echo "Connected to Database <br />";
$lcusername = strtolower($username);
$esclcusername = mysql_real_escape_string($lcusername);
$escpassword = mysql_real_escape_string($password);
$result = mysql_query("SELECT * FROM userdb WHERE username='$esclcusername' AND password='$escpassword'") or die(mysql_error());
$row = mysql_fetch_array( $result );
$validateUser = $row['username'];
$validatePass = $row['password'];
The POST data is from the previous log in page. I want this script to check the table (userdb) and find the row for the username that the user entered from the previous form and verify that the password entered matches the username's password set in that row, in userdb table.
I also want some type of way to check whether or not if the username entered exists, to tell the user that the username entered does not exists if it can not be found in the table.
This is not a direct answer to this question but a GOOD value-add.
You should use MYSQL SHA1 function to encrypt the password before storing into the database.
$user = $_POST['userid'];
$pwd = $_POST['password'];
$insert_sql = "INSERT into USER(userid, password) VALUES($user, SHA1($pwd))";
$select_sql = "SELECT * FROM USER WHERE userid=$user AND password=SHA1($pwd))";
You can use sessions. Sessions are global variables that when set, stay with the user while he is browsing through the site.
Since you are learning PHP, try out this tutorial on the official website.
But what you would do in theory is when the username and password match, you set a session variable
$_SESSION["auth"] = true;
$_SESSION["user_id"] = $row["user_id"];
And then do a check to see if the user is authenticated.
One way to do it (DISCLAIMER: not necessarily best-practice):
$result = mysql_query("SELECT id FROM userdb WHERE username='$esclcusername' AND password='$escpassword'") or die(mysql_error());
$row = mysql_fetch_array( $result );
$id = (int)$row['id'];
if($id > 0) {
//log in the user
session_start();
$_SESSION['userId'] = $id;
$_SESSION['username'] = $displayname;
}
... and on pages that require authentication:
session_start();
if(!isset($_SESSION['userId'])) {
die('You need to be logged in!!!');
} else {
echo 'Welcome ' . $_SESSION['username'];
}
Read more about PHP sessions.
I like to use both $_SESSION and MYSQL Checks with any login POST. This should help get a few things started.
$username = mysql_real_escape_string($_POST[username]);
$password = strip_tags($_POST[password]);
$password = sha1($password);
if(isset($username) && isset($password) && !empty($username) && !empty($password))
{
$sql = mysql_query("SELECT * FROM users_column WHERE username = '$username' AND password = '$password'");
//Check the number of users against database
//with the given criteria. We're looking for 1 so
//adding > 0 (greater than zero does the trick).
$num_rows = mysql_num_rows($sql);
if($num_rows > 0){
//Lets grab and create a variable from the DB to register
//the user's session with.
$gid = mysql_query("SELECT * FROM users_column WHERE username = '$username' AND password = '$password'");
$row = mysql_fetch_assoc($gid);
$uid = $row[userid];
// This is where we register the session.
$_SESSION[valid_user] = $uid;
//Send the user to the member page. The userid is what the
//session include runs against.
header('Location: memberpage.php?userid='.$userid);
}
//If it doesn't check out -- throw an error.
else
{
echo 'Invalid Login Information';
}
}
NOTE: You would need to start the page file with session_start() and create a separate Session Check include stating with session_start() and then your progressions e.g. if($_SESSION[valid_user] != $userid) do something.
You could use a select statement to retreive from MySQL the password for the specified username. If you have an empty result set, then you do not have the username in the table.
If you need the user to be authenticated in more than one php page, then one choice whould be using sessions (http://www.php.net/manual/en/function.session-start.php).
Also, I think you should think about security, i.e. preventing SQL injection:
$variable = mysql_real_escape_string($_POST['variable'])
and avoiding to "die" (treating errors and returning user-friendly messages from the script).
I would also think about not storing passwords in your database. One way hashes with MD5 or SHA1 are a way of adding a layer of security at the db level.
See http://php.net/md5 or http://php.net/sha1 for further information.
I agree with the idea if using SESSION variables while authenticating the user.
The easy way to authenticate the user is as follows
//connect the mysql_db
$mysql_connect()
$mysql_select_db()
//reading from mysql table
$res="SELECT * FROM table WHERE name=$username AND password=$password";
$val=mysql_query($res);
//authentication
$count=mysql_num_rows($val);
if($count==1)
//authenticate the user
else
through an error