<?php
// auth.php

// start session
session_start(); 

// convert username and password from _POST or _SESSION
if($_POST){
  $_SESSION['username']=$_POST["username"];
  $_SESSION['password']=$_POST["password"];  
}

// query for a user/pass match
$result=mysql_query("select * from users 
  where username='" . $_SESSION['username'] . "' and password='" . $_SESSION['password'] . "'");

// retrieve number of rows resulted
$num=mysql_num_rows($result); 

// print login form and exit if failed.
if($num < 1){
  echo "You are not authenticated.  Please login.<br><br>
  
  <form method=POST action=admin.php>
  username: <input type=text name=\"username\">
  password: <input type=password name=\"password\">
  <input type=submit>
  </form>";
  
  exit;
}
?>

This code prompt out username and password if there is no session found, but if u entered a wrong username, password or even leave in blank, it will just do nothing. How to do user input error checking, like empty username/password, imvalid password.

Please advise.

if(empty($_POST['username'])){
echo"Please enter username";
}
if(empty($_POST['password'])){
echo"Please enter password";
}

Obviously, you could do a lot of other checks like verifying the number of characters in each field with strlen. I just listed what you asked. I would recommend that you take some basic actions against SQL injection. The function mysql_real_escape_string does a pretty good job. It should be put in after a connection to mysql has been established and before or during the query. Here is a link to the function's documentation.

mysql_real_escape_string(htmlspecialchars($_SESSION['username']));
mysql_real_escape_string(htmlspecialchars($_SESSION['password']));

If you don't do this, a user could put ' OR ''=' in the password field and the query would let a person login without a password.

Thanks buddylee17, the thing is, I'm calling this auth.php in every page, I've already tried the method you mentioned above, after you logged in successfully, The echo statements will be on every page that includes auth.php. Any other suggestions?

Not sure I understand your situation. How about a redirect to the login if the session isn't valid?

if(empty($_SESSION['username']) || empty($_SESSION['password'])){
header ('Location:login.php?please_login');
}

Situation:

The auth.ph was placed on every single page of my except the index.html and logout.php. I want to access direct to an admin type page (e.g. localhost/cycle/addlist.php) it would prompt a login message. If I place the

if(empty($_POST['username'])){
echo"Please enter username";
}

even after I logged in with correct username and password, the echo will be displayed on addlist.php.

This article has been dead for over six months. Start a new discussion instead.