User Authentication for a PEAR CMS - String or Numeric
(Page 3 of 4 )
After determining whether the values entered are not empty, we check to see if the values entered here are string or numeric. Since we only expect values that are of type string, it is easy to check with the is_numeric() function, which evaluates the parameter that it is passed:
//make sure fields are string
if(is_numeric($_POST['uname'])){
$err=true;
$error .="The username you entered has a invalid format.<br>";
}
if(is_numeric($_POST['upass'])){
$err=true;
$error .="The password that you entered has an invalid format<br>.";
}
If the passed values are not of type string, then we set the $err variable to true. Later on in the script we will test this Boolean variable to determine if certain actions should be taken. The code then checks to see if the $err variable is true or false and then proceeds accordingly. If the $err variable is true then it means somewhere along the line there was an error, therefore we cannot continue with the SQL query to check if the user exists in the database. On the other hand, if there was no error, the code continues to call the db class and connx.php file to run a query:
if(!$err){
include 'db.php';
include 'connx.php';
As already discussed, the db class contains methods that we will be using to run database queries, and the connx.php file contains the database connection information that is needed to connect to the database. Once the data is available to the script, it is used for the sql query. Since we are using data that is coming from an untrusted source (in this case the HTML form), it has to be filtered. In our case we have two pieces of information coming from outside the application, the username and password. This data will be used in the SQL query, we need to filter these items. To filter the data we use the mysq_real_escape_string() function as shown in the code below:
$username=mysql_real_escape_string($_POST['uname']);
$pw=mysql_real_escape_string($_POST['upass']);
Once the data is filtered, we then run a query to determine if this user exists in the database:
$sql = "SELECT * FROM users WHERE uname='".$username."' AND upass='".$pw."'";
$res = $db->query($sql);
We then check to see if any errors have been returned while executing the query. We do this by checking DB's isError() function and then printing out the message:
if (DB::isError($res)) {
die($res->getMessage());
}
//***********************************************************
Next: Granting Access to the CMS >>
More PEAR Articles Articles
More By David Web