{"id":1430,"date":"2008-03-25T23:02:39","date_gmt":"2008-03-26T04:02:39","guid":{"rendered":"http:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/authentication-with-phpmysql"},"modified":"2013-12-07T19:39:49","modified_gmt":"2013-12-08T00:39:49","slug":"authentication-with-phpmysql","status":"publish","type":"post","link":"https:\/\/teamtutorials.com\/web-development-tutorials\/php-tutorials\/authentication-with-phpmysql","title":{"rendered":"Authentication with PHP\/MySQL"},"content":{"rendered":"
Warning:<\/strong> This tutorial uses old techniques. It is insecure and will leave your server vulnerable to SQL Injection attacks<\/strong>.This tutorials also uses mysql_ functions that are no longer support. For updated tutorials look for a PDO<\/a> or MySQLi tutorial.This post will be delete or revised in the future.<\/p>\n<\/div>\n This tutorial will walk you through setting up a database and using it to authenticate users to your site. This will allow only certain pages to be seen by users that have legitimate passwords. Once you read this tutorial you will be able to understand the basics of sessions which pass the authentication from page to page. There are several ways to improve and\/or make the system better, but I’ll leave that to you. \ud83d\ude42 Make sure you follow John’s php tutorials to understand the concepts we will be using:<\/p>\n MyAdmin Database Construction<\/a> First we need to set-up our database. All we need is a database with the fields of Username, PW, and ID number (which will auto-increment to be the Primary Key which has to be Unique.) The password field needs to accept a lot of characters (100 or more) because we are going to encrypt them. You could add other things like an approved option that once a user signs up you would have to approve them before they have access, but for the sake of this tutorial, we are going to keep it simple. <\/p>\n First, we need to create a temp file that will allow us to add a user to the database. We are going to encrypt our passwords using SHA1 so we wont be able to manually add them into the database. To do this we need to make a file that will run the SHA1 algorithm on whatever text in in the input box. I called this file tt.php. On pressing of the submit button it will send us to insert.php. All we need in the first file is some simple html as shown below:<\/p>\n This file should look like this when opened: Next we need to create insert.php which will be called when the Create User button is pressed. This file will start with the following:<\/p>\n The above code will set the variable $user_name equal to the value of the user name form on the last page. Ensure that your input boxes on the last page match what you put in single quotes within the POST command. They are case sensitive.<\/p>\n This initaites the connection to our database so that we can insert the values into the database.<\/p>\n This snippet of code will check to make sure that the variables that we set have values and were not left blank. It will prompt you to go back and change the entries. If either is empty, it will stop parsing the php and the rest of the file will not be executed. (**For some reason the code converter that we use here at TeamTutorials is showing “empty” twice. There should only be one**)<\/p>\n This code inserts the values of the variables into the database. Please note that there are several ways to include variables in a php\/mysql statement. This is just one of those ways. <\/p>\n This will echo the values of the data inserted into the database if the php completes. Once you see these values, you should have an additional entry in your database. The last step is to create our authentication file. There are several ways to do this. The way we are going to do it is to send them to a failed page on failure and to a success page on success. We will call this file login.php.<\/p>\n This should be the first line of the php file. It need to be parsed before ANY header information is sent to the browser. This starts the session. This will allow the authentication to be passed from page to page. <\/p>\n As you can see we set up the input boxes almost the same as our user creation file. Once they hit submit it will send them to session.php. Let’s make that file now:<\/p>\n This code does several things. It first, sets the variables equal to the values of the input forms on the last page. Next it creates the connection to the database. Then it queries for a count (which will return the number of results that match the username and sha’d version of the text entered). If then sets the results equal to a variable and checks the variable. If it is equal to 0 it sends it to the failure page and if it equals anything other than 0 it sends it to the welcome page. The last things we need to do are make the welcome page and the logout page. Since we set the session variable, all we have to do is check that for a value and if it exists they are currently logged in. <\/p>\n This checks to see if the value is set and if it is show them the welcome message. If it is not set (if someone went straight to the index.php file rather than going to login.php) it would tell them to log in first.<\/p>\n This concludes this tutorial. There are a lot of conecpts given here than can be hard to grab until you get used to them. I hope that you were able to follow this tutorial and that it will help you on your way. Please feel free to comment with your results and your recommendations. Thank you for reading. <\/p>\n","protected":false},"excerpt":{"rendered":" This tutorial will walk you through setting up a database and using it to authenticate users to your site. This will allow only certain pages to be seen by users that have legitimate passwords. <\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[24],"tags":[],"yoast_head":"\n
\nAccess Database with PHP<\/a>
\nCreating Data for Database in PHP<\/a><\/p>\n\r\n\r\n<form method="post" action="insert.php">\r\n\r\nFull Name: (Example: Michael R Maguire) <br \/>\r\n\r\n<input type="text" name="user_name" size="50" maxlength="50"\/> (50 Characters Max)\r\n\r\n<br \/>\r\n<br \/>\r\n\r\nUser Name: <br \/>\r\n\r\n<input type="text" name="SHA_PW" size="20" maxlength="20"\/> (20 Characters Max)\r\n\r\n<br \/>\r\n<br \/>\r\n\r\n<input type="submit" value="Create User" \/>\r\n\r\n<\/form>\r\n<\/pre>\n
\n<\/p>\n\r\n<?php\r\n$user_name = $_POST['User_name'];\r\n$SHA_PW = $_POST['SHA_PW'];\r\n<\/pre>\n
\r\n$dbname = "teamtutorials_test";\r\n$conn = mysql_connect ("localhost","teamtutorials_test","tutorial") or \r\ndie ('cannot connect to database error: '.mysql_error());\r\nmysql_select_db ($dbname);\r\n<\/pre>\n
\r\nif(empty($user_name) || empty($SHA_PW)) {\r\necho "<h2>Please fill in all fields<\/h2>\\n";\r\necho "Please use the back button in your browsers and fill in all required fields.\\n";\r\ndie ();\r\n}\r\n<\/pre>\n
\r\n<?php\r\n$sql ="INSERT INTO `teamtutorials_test`.`users` ( `User_ID` , `user_name` , `sha_pw`) VALUES (\r\nNULL, '".$user_name."' ,'".sha1($SHA_PW)."');\r\nmysql_query($sql) or die ('update failed: '.mysql_error())\r\n?>\r\n <\/pre>\n
\r\n<?php\r\necho "User Name: $user_name";\r\necho "Sha Password: ".sha1($SHA_PW);\r\n?>\r\n <\/pre>\n
\r\n<?php\r\n\r\nsession_start();\r\n\r\n?>\r\n <\/pre>\n
\r\n\r\n<form method="post" action="session.php">\r\n\r\nFull Name: (Example: Michael R Maguire) <br \/>\r\n\r\n<input type="text" name="user_name" size="50" maxlength="50"\/> (50 Characters Max)\r\n\r\n<br \/>\r\n<br \/>\r\n\r\nUser Name: <br \/>\r\n\r\n<input type="text" name="password" size="20" maxlength="20"\/>\r\n\r\n<br \/>\r\n<br \/>\r\n\r\n<input type="submit" value="Create User" \/>\r\n\r\n<\/form>\r\n\r\n<\/pre>\n
\r\n<?php\r\n\r\nsession_start(); \r\n\r\nif (isset($_POST['username']) && isset($_POST['password'])) \r\n{\r\n$username = $_POST['username']; \r\n$password = $_POST['password']; \r\n\r\n$conn = mysql_connect ("localhost","teamtutorials_test","tutorials") or \r\ndie ('cannot connect to database error: '.mysql_error());\r\n \r\n$sql = mysql_query("select count(*) from users \r\nwhere user_name = '$username' and sha_pw = sha1('$password')") or die(mysql_error()); \r\n\r\n$results = mysql_result($sql, "0"); \r\n\r\nif ($results == 0){ \r\nheader( 'Location:http:\/\/teamtutorials.com\/tutorials\/loginfailed.php');\r\n}\r\nelse \r\n{\r\n$_SESSION['valid_user'] = $username \r\nheader( 'Location:http:\/\/teamtutorials.com\/tutorials\/members.php'); \r\n}\r\n}\r\n?>\r\n<\/pre>\n
\r\n<?php\r\n\r\nsession_start(); \r\n\r\nif (isset($_SESSION['valid_user']))\r\n{\r\necho 'Welcome to the members section.';\r\n}\r\nelse\r\n{\r\necho 'You are not logged in. Please login first.';\r\n}\r\n?>\r\n<\/pre>\n