Saturday, April 19, 2008 BDPA – Sothern Minnesota PHP/MYSQL USER AUTHENTICATION Setting up the database Although this has already been done for you, typically the first step is creating the database: CREATE DATABASE `login`; For this assignment you will be accessing the database yctp_bdpa Next you want to create the table with the column headings username, a password, and an email. All of the values stores in the columns are of the type variable character (i.e. varchar). Note: Null is defined as not having a value. In MySQL Not Null is used to initialize the values to something other than “no value”. CREATE TABLE `users` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `username` VARCHAR( 255 ) NOT NULL , `password` VARCHAR( 255 ) NOT NULL , `email` VARCHAR( 255 ) NOT NULL ) In this code, the table users is created. The id is a mandotory value and is used as a primary key. A primary key uniquely identify a row in a table. One or more columns may be identified as the primary key. The values in a single column used as the primary key must be unique (like a person's social security number). When more than one column is used, the combination of column values must be unique. Username, password and email are the fields you want to store data in. They’re given a allowance of 255 characters in a single field. Each time new data is stored, the id auto increments, which means the id will increment with ‘one’. Creating the database connection Creating the database connection is the same as you did for your earlier assignments. Enter the following code, but with your own username and password. <?php // Your host, 99% of the time it's localhost. $db_host = 'localhost'; // Your username for MySQL. $db_user = 'user'; // Your password for MySQL. $db_pass = 'pass'; // And your given name for the database. $db_name = 'login'; // The database connection. $con = mysql_connect($db_host, $db_user, $db_pass); if(!$con) { die("Cannot connect. " . mysql_error()); } // The database name selection. $dbselect = mysql_select_db($db_name); if(!$dbselect) { die("Cannot select database " . mysql_error()); } ?> Creating the registerform Create an empty PHP page with the name ‘register.php’ and write the following code within the <body> tags. <form method="post" action="authenticate.php"> <!-- you can use another action if you'd like --> <label for="username">Username: </label><br /> <input type="text" name="username" id="username"><br /> <label for="password">Password: </label><br /> <input type="password" name="password" id="password"><br /> <label for="password2">Confirm: </label><br /> <input type="password" name="password2" id="password2"><br> <label for="email">Email address:</label><br /> <input type="text" name="email" id="email"><br /> <input type="submit" name="submit" id="submit" value="Submit"> </form> Handle the registerform Now it gets interesting. Create another empty PHP page and name it after the action given in the <form action=”"> tag. If following along with the above code the page would be named ‘authenticate.php’. Example Code <?php // Include the database connection file. include("connection.php"); // Check if a person has clicked on submit. if(isset($_POST['submit'])) { // Check if a person has filled every form. if(empty($_POST['username']) || empty($_POST['password']) || empty($_POST['password2']) || empty($_POST['email'])) { // Display the error message. echo "You have to fill in everything in the form."; // Exit the code. exit; } // Create variables from each $_POST. $username = $_POST['username']; $password = $_POST['password']; $password2 = $_POST['password2']; $email = $_POST['email']; // Now, compare passwords and check if they're the same. if($password != $password2) { // If the passwords are NOT the same. Again display an error message and redirect. echo "Sorry, wrong password."; exit; } // Secure the password using an md5 hash. $password = md5($password); // Create a variable containing the SQL query. $query = "INSERT INTO `users` (username, password, email) VALUES ('$username', '$password', '$email')"; // Perform the SQL query on the database. $result = mysql_query($query); // If the query failed, display an error. if(!$result) { // The dot seperates PHP code and plain text. echo "Your query failed. " . mysql_error(); } else { // Display a success message! echo "Welcome " . $username . " You are now registered"; } } ?> Comments By filling in the registerform. The data from the regsiterform is posted to the PHP file ‘authenticate.php’ and processed. The data is then stored into the database, in the table ‘users’. The user will now be able to log in Security Generally from a security standpoint you NEVER EVER submit data which is filled out by user without validating them and replace certain tags! When you assign the $username and $password variable, you can give them a basic security. e.g $username = mysql_real_escape_string($_POST[’username’]; $password = mysql_real_escape_string($_POST[’password’]; Escapes special characters in the unescaped_string , taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used. Handling Duplicate Usernames When checking if the desired username already exists try: $sql = “SELECT username FROM users WHERE username=’$username’”; if($sql) { echo “Username already exists”; } else { echo “Username doesn’t exist”; } Creating the loginform <form method="post" action="login2.php"> <label for="username">Username: </label><br /> <input type="text" name="username" id="username"><br /> <label for="password">Password: </label><br /> <input type="password" name="password" id="password"><br /> <input type="submit" name="submit" id="submit" value="Submit"> </form> Handle the loginform <?php // login2.php include("connection.php"); // Start a session. Session is explained below. session_start(); // Same checking stuff all over again. if(isset($_POST['submit'])) { if(empty($_POST['username']) || empty($_POST['password'])) { echo "Sorry, you have to fill in all forms"; exit; } // Create the variables again. $username = $_POST['username']; $password = $_POST['password']; // Encrypt the password again with the md5 hash. // This way the password is now the same as the password inside the database. $password = md5($password); // Store the SQL query inside a variable. // ONLY the username you have filled in is retrieved from the database. $query = "SELECT username,password FROM `users` WHERE username='$username'"; $result = mysql_query($query); if(!$result) { // Gives an error if the username given does not exist. // or if something else is wrong. echo "The query failed " . mysql_error(); } else { // Now create an object from the data you've retrieved. $row = mysql_fetch_object($result); // You've now created an object containing the data. // You can call data by using -> after $row. // For example now the password is checked if they're equal. if($row->password != $password) { echo "I am sorry, but the passwords are not equal."; exit; } // By storing data inside the $_SESSION superglobal, // you stay logged in until you close your browser. $_SESSION['username'] = $username; $_SESSION['sid'] = session_id(); // Make it more secure by storing the user's IP address. $_SESSION['ip'] = $_SERVER['REMOTE_ADDR']; // Now give the success message. // $_SESSION['username'] should print out your username. echo "Success! You are now logged in " . $_SESSION['username']; } } ?>