old_blueyes Posted September 28, 2015 Share Posted September 28, 2015 (edited) Hi, Just wondering if someone could point me in the right direction, I have a simple PHP MySQL login script which passes/stores data via sessions. It works fine, there is no problem with it. All I would like to do is pass some additional data from the users MySQL table. Currently it users just username and password, but I would like it to pass firstname and surname data as well. So when a user logs in with their username and password, on the next page it might say Welcome, Michael Smith. The script below is originally setup for the username to be a persons name, as it's used in the login welcome message in the login.php But I might change the username to be an email address, if I can pull in the additional data. config.php <?php /***************************** File: includes/config.php Written by: Frost of Slunked.com Tutorial: User Registration and Login System ******************************/ // start the session before any output. session_start(); // Set the folder for our includes $sFolder = '/predictor/login'; /*************** Database Connection You will need to change the user (user) and password (password) to what your database information uses. Same with the database name if you used something else. ****************/ mysql_connect('localhost', 'root', '') or trigger_error("Unable to connect to the database: " . mysql_error()); mysql_select_db('football') or trigger_error("Unable to switch to the database: " . mysql_error()); /*************** password salts are used to ensure a secure password hash and make your passwords much harder to be broken into Change these to be whatever you want, just try and limit them to 10-20 characters each to avoid collisions. ****************/ define('SALT1', '24859f@#$#@$'); define('SALT2', '^&@#_-=+Afda$#%'); // require the function file require_once($_SERVER['DOCUMENT_ROOT'] . $sFolder . '/includes/functions.php'); // default the error variable to empty. $_SESSION['error'] = ""; // declare $sOutput so we do not have to do this on each page. $sOutput=""; ?> login.php <?php /***************************** File: login.php Written by: Frost of Slunked.com Tutorial: User Registration and Login System ******************************/ require($_SERVER['DOCUMENT_ROOT'] . '/predictor/login/includes/config.php'); // If the user is logging in or out // then lets execute the proper functions if (isset($_GET['action'])) { switch (strtolower($_GET['action'])) { case 'login': if (isset($_POST['username']) && isset($_POST['password'])) { // We have both variables. Pass them to our validation function if (!validateUser($_POST['username'], $_POST['password'])) { // Well there was an error. Set the message and unset // the action so the normal form appears. $_SESSION['error'] = "Bad username or password supplied."; unset($_GET['action']); } }else { $_SESSION['error'] = "Username and Password are required to login."; unset($_GET['action']); } break; case 'logout': // If they are logged in log them out. // If they are not logged in, well nothing needs to be done. if (loggedIn()) { logoutUser(); $sOutput .= '<h1>Logged out!</h1><br />You have been logged out successfully. <br /><h4>Would you like to go to <a href="index.php">site index</a>?</h4>'; }else { // unset the action to display the login form. unset($_GET['action']); } break; } } $sOutput .= '<div id="index-body">'; // See if the user is logged in. If they are greet them // and provide them with a means to logout. if (loggedIn()) { $sOutput .= '<h1>Logged In!</h1><br /><br /> Hello, ' . $_SESSION["username"] . ' how are you today?<br /><br /> <h4>Would you like to <a href="login.php?action=logout">logout</a>?</h4> <h4>Would you like to go to <a href="index.php">site index</a>?</h4>'; }elseif (!isset($_GET['action'])) { // incase there was an error // see if we have a previous username $sUsername = ""; if (isset($_POST['username'])) { $sUsername = $_POST['username']; } $sError = ""; if (isset($_SESSION['error'])) { $sError = '<span id="error">' . $_SESSION['error'] . '</span><br />'; } $sOutput .= '<h2>Login to our site</h2><br /> <div id="login-form"> ' . $sError . ' <form name="login" method="post" action="login.php?action=login"> Username: <input type="text" name="username" value="' . $sUsername . '" /><br /> Password: <input type="password" name="password" value="" /><br /><br /> <input type="submit" name="submit" value="Login!" /> </form> </div> <h4>Would you like to <a href="login.php">login</a>?</h4> <h4>Create a new <a href="register.php">account</a>?</h4>'; } $sOutput .= '</div>'; // lets display our output string. echo $sOutput; ?> functions.php <?php /***************************** File: includes/functions.php Written by: Frost of Slunked.com Tutorial: User Registration and Login System ******************************/ /*********** bool createAccount (string $pUsername, string $pPassword) Attempt to create an account for the passed in username and password. ************/ function createAccount($pUsername, $pPassword, $pFirstname, $pSurname) { // First check we have data passed in. if (!empty($pUsername) && !empty($pPassword) && !empty($pFirstname) && !empty($pSurname)) { $uLen = strlen($pUsername); $pLen = strlen($pPassword); $fLen = strlen($pFirstname); $sLen = strlen($pSurname); // escape the $pUsername to avoid SQL Injections $eUsername = mysql_real_escape_string($pUsername); $sql = "SELECT username FROM users WHERE username = '" . $eUsername . "' LIMIT 1"; // Note the use of trigger_error instead of or die. $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); // Error checks (Should be explained with the error) if ($uLen <= 4 || $uLen >= 11) { $_SESSION['error'] = "Username must be between 4 and 11 characters."; }elseif ($pLen < 6) { $_SESSION['error'] = "Password must be longer then 6 characters."; }elseif (mysql_num_rows($query) == 1) { $_SESSION['error'] = "Username already exists."; }else { // All errors passed lets // Create our insert SQL by hashing the password and using the escaped Username. $sql = "INSERT INTO users (`username`, `password`, `firstname`, `surname`) VALUES ('" . $eUsername . "', '" . hashPassword($pPassword, SALT1, SALT2) . "', '" . $pFirstname . "', '" . $pSurname . "');"; $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); $sql2 = "INSERT INTO predictions (userID, predictionID, week) SELECT LAST_INSERT_ID(), id, week FROM fixtures"; $query = mysql_query($sql2) or trigger_error("Query Failed: " . mysql_error()); if ($query) { return true; } } } return false; } /*********** string hashPassword (string $pPassword, string $pSalt1, string $pSalt2) This will create a SHA1 hash of the password using 2 salts that the user specifies. ************/ function hashPassword($pPassword, $pSalt1="2345#$%@3e", $pSalt2="taesa%#@2%^#") { return sha1(md5($pSalt2 . $pPassword . $pSalt1)); } /*********** bool loggedIn verifies that session data is in tack and the user is valid for this session. ************/ function loggedIn() { // check both loggedin and username to verify user. if (isset($_SESSION['loggedin']) && isset($_SESSION['userID']) && isset($_SESSION['username'])) { return true; } return false; } /*********** bool logoutUser Log out a user by unsetting the session variable. ************/ function logoutUser() { // using unset will remove the variable // and thus logging off the user. unset($_SESSION['username']); unset($_SESSION['userID']); unset($_SESSION['loggedin']); return true; } /*********** bool validateUser Attempt to verify that a username / password combination are valid. If they are it will set cookies and session data then return true. If they are not valid it simply returns false. ************/ function validateUser($pUsername, $pPassword) { // See if the username and password are valid. $sql = "SELECT * FROM users WHERE username = '" . mysql_real_escape_string($pUsername) . "' AND password = '" . hashPassword($pPassword, SALT1, SALT2) . "' LIMIT 1"; $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); // If one row was returned, the user was logged in! if (mysql_num_rows($query) == 1) { $row = mysql_fetch_assoc($query); $_SESSION['username'] = $row['username']; $_SESSION['userID'] = $row['userID']; $_SESSION['password'] = $row['password']; $_SESSION['loggedin'] = true; return true; } return false; } ?> USERS TABLE ID username password firstname surname 1 rich 12345 Richard Branson 2 alan 67898 Lord Sugar Edited September 29, 2015 by Ch0cu3r Added code tags Quote Link to comment Share on other sites More sharing options...
benanamen Posted September 29, 2015 Share Posted September 29, 2015 (edited) there is no problem with it. Actually there are several problems with it. Your code is obsolete and will not work in PHP7. It is insecure and you should not be using it. You need to use PDO with prepared statements or at the least Mysqli with prepared statements. SHA1 is not secure, you should be using Brypt. Edited September 29, 2015 by benanamen Quote Link to comment Share on other sites More sharing options...
scootstah Posted September 29, 2015 Share Posted September 29, 2015 You need to modify this part to add additional items to $_SESSION: if (mysql_num_rows($query) == 1) { $row = mysql_fetch_assoc($query); $_SESSION['username'] = $row['username']; $_SESSION['userID'] = $row['userID']; $_SESSION['password'] = $row['password']; $_SESSION['loggedin'] = true; return true; } Quote Link to comment Share on other sites More sharing options...
Jacques1 Posted October 1, 2015 Share Posted October 1, 2015 I'll have to agree with benanamen that this code is poorly written and shouldn't be used at all. If you intend to use this for a real application, it's way too insecure and will put your users' data in jeopardy. And if this is just for learning, you're better off writing your own code with modern features like the password hash API. It's generally a bad idea to just copy-and-paste code you found somewhere on the Internet. Most of it was written by amateurs many years ago and hasn't been updated since. A better approach is to do your own research and look for projects which are actively maintained on a platform like GitHub (preferrably by more than one person). Do you need this for an actual application? Do you have the time to learn the basics and write this yourself, or do you want a premade solution? Quote Link to comment Share on other sites More sharing options...
QuickOldCar Posted October 1, 2015 Share Posted October 1, 2015 Agree with the others. That tutorial is almost 6 years old now, that's an eternity in coding time. When looking for registration tutorials look for PDO and password_hash() and should be a better start for you. Also a lot of tutorials are written as an example of how to accomplish something, is up to you to ensure are safe and secure. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.