7. PHP Tutorial - Log In Form - Log Out Script - Cookies and Sessions - User Profile

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to web intersect 2.0 social network website production series part 7 in this part we will cover the login mechanics redirecting the user to a placeholder profile page if their login is successful we'll also cover the logout script in this video and we will create a module for verifying the user in situations where you must double check their credentials before running some code before we do those things we're going to very quickly edit just a couple of lines of code from the last web intersect video number 6 because I was in a hurry and I forgot to initially make database fields to store the unique salts and a reference token separate from the cryptid hash so I'm not going to sit here and pretend that I'm the world's leading authority on PHP password encryption because I'm not nor do I wish to spend any more time covering password encryption I just know my fair share I've done my fair share of experiments in reading that's it so in light of that just so we can move along with creating other software systems for the social network I've decided to give you all of the information on this whole password encryption matter direct from the horse's mouth and just let you guys decide for yourselves individually okay here's the page the URL that I want you to go to at the PHP official documentation manual and you should just really listen to what they recommend so it says safe password hashing this section explains the reasons behind using hashing functions to secure passwords as well as how to do so effectively so you have why should i hash my password supplied by users of my application why are common hashing functions such as md5 and sha-1 unsuitable for passwords you can see that they recommend crypt and hash over md5 and sha-1 of this you can read about what a salt is read all the users supplied comments and just do some general googling to get yourself in the know about password or general data encryption or whenever you need to secure some data on your website now I can show you guys ways but like I said I'm not a password encryption top expert but I can show you ways to complexify md5 and sha-1 you can render out an md5 hash and chop it up into little pieces and disperse it all throughout a very long string and nobody will ever know where those little segments of the actual hash are living within that string so there's there are things you can do in a custom sense to complexify md5 and sha-1 a recommend crypt or hash for securing user passwords and this also I think WordPress uses some popular PHP password hashing mechanism and you can look into what WordPress is using for that so since I forgot to initially make database fields to hold unique salts and tokens for each user's password encryption this lesson series will just use basic md5 hash so that we can continue without me having to go back to video 1 so now go into signup PHP and somewhere around line 73 we're going to comment this out or just remove them altogether you see where we're generating P hash the password hash from the crypt function we're going to remove that and just add this line so we have P hash md5 on the password and that will hash the password before it gets inserted into the database now this is a very basic and not the most secure way to hash a password for secure storage in your system so this me putting this in place will assure that you guys all do your homework on your own and you come up with your own unique way of salting your cryptic passwords so if I'm not offering a method for you guys to secure your passwords you will not have any security problems that people know that you're running a software that's based off of the web intersect tutorial series if somebody happens to see that you might be running your system based off of this software series they won't know what kind of password encryption method you are using at all so while you're in production if you just want to see all your systems working go along with the tutorial series with me you can use md5 for now and later on when you become a super expert in PHP password encryption then you go back and change it just make your system a little more secure I gave you all of the information you can go and read it yourself and all you got to do is really Google so make sure you go in to sign up PHP and change that like I just did now the next line I want you to change is within activation dot PHP so open up activation dot PHP and go to the section where it says evaluate the lengths of the incoming get variables change this one to if string length P is not equal to 74 because ours won't be equal to 74 anymore so you can just say if P is equal to nothing so you just want to check and see if it's empty and later on when you complexify your system you can change this to maybe match a certain exact length like we were doing before it okay so if you've changed sign up that PHP and activation dot PHP your system will work now with the login script that I'm about to show you and then after you complexify your password storage mechanisms you would also alter your login script and you'll want to replace activation dot PHP and signup dot PHP on your server right now now before we can continue you have to go into your database go into PHP myadmin and you want to empty the users table just click empty right there truncate users okay and then empty the user options table as well so that way you're back to a clean slate okay and also be very sure that you go right now into your folder system online into the users folder and remove any of the dummy folders or the test account folders that were created when you signed up and then when you remove that folder go ahead and signup again to your site navigate to signup dot PHP and run through the process again and get yourself as a user in the system once again alright so I got the message okay Adam check your email inbox now go ahead and make a few more dummy accounts make about three or four different dummy accounts using different email addresses this way you'll have a few different users within your system to see how things work especially when you go to create your friends system and things like that you'll want to have multiple dummy users in there to do some testing so make several accounts right now alright so when you click the link within your activation email you'll see activation success and your account is now activated click here to login so you see now we have the login page up and this is what we're going to be explaining within this video so this one is similar to the signup page uses Ajax and if you don't put data in click that it says fill out all the form data you can go ahead and put in your data and the pro got password link is not established yet because that script is coming a little bit later in the series so I'm going to put in my credentials and then press login and upon successful login I'm assured to my profile page which is user dot PHP which I'm going to be giving you all the code for and it's just a basic default placeholder page for now which we're going to expand later on but I just wanted to show you how after they login you can redirect them to directly to their profile if you want and we have our module in place that verifies the user in certain situations where you want to double-check their credentials before you show them things or give them certain profile options so it says is the viewer the page owner logged in and verified it says yes so if you were viewing this profile right now you're not logged in as Adam so this would say no so with that logic you can give the user if this is yes you can give the user profile editing buttons and things like that that normal users viewing their profile would never see ok so you'll be getting that login script you'll be getting the and actually there's a logout script let me show you how that works I'm going to just going to go to logout dot PHP but you'll have links to it eventually I'm just going to go directly to it logout dot PHP and you can do the same while you're in production and you see it logged me out and put me back at the home page of web intersect now if I try to go to user Adam it says is the view of the page owner logged in and verified no because I'm not logged in anymore I just logged out so the logout script works and you'll get your hands on that within this video as well so all that's left now is to discuss the code really quickly from these new four files that you're going to be receiving ok the first file you will receive is login type PHP now let's explain the login form now some people like to make a login form just send up a box that magically appears somewhere near the header some people you'll see they'll have in the header of their site two fields where the user can login directly but I'm just going to have a separate page with a login form on it after you get really good at web development you can just put your form wherever you want it it doesn't have to be on its own separate page okay so the login form you can see it has ID of login form and on submit we have return false that way it doesn't process in the normal way because it's going to be Ajax processing so let's open this up and check out the fields the first input field we have is for their email address and in the onfocus event when the user goes to put the cursor in and type into the field that's when the on focus event fires off you want to empty the status element the status element is down here and that's the element that all the error handling and messages to the user as they're filling out the form that's where those messages will go so if they're login is unsuccessful the message goes there so when they go to put the cursor back in those fields in the on focus event you want to empty out that message because they're trying to fix whatever the problem was so you don't need that message there anymore so you empty the element status and you can see the same happens for the password field and I should remove all the max lengths and I even I think on the signup form I had a max length on the password you really shouldn't have a max length let's go ahead and give that 100 that way the password can be really long hey look I'm going to open sign up that PHP I'm going to go down into the form and that one too and I think C for the password where we have C max length change this to 100 or 200 whatever so you don't have to really restrict the length of their password since it's all going to be hashed anyway to a certain bit length and then you have the login button which in the on click event fires off the JavaScript function login and that's where your Ajax is I'm going to show you that login function in just a sec that's sitting right here and then the last thing in the form is a little link to your forgot password page or whatever your forgot password form and that you can just stick in the URL to that when we make it later on so you don't really even have to have that link in there but I just went ahead and put it in there because we're going to be sticking a URL in there pretty soon all right so you see that's the whole stinking login form and here up in the head tag you have some CSS that's styling that login form very basic stuff so let's talk about that login function okay now function login works exactly the same way that our function signup did on signup dot PHP what we do is we scooped up the variables from the form fields but you're scooping up the value of each form field and you're putting into a local JavaScript variable then you're saying if if the email variable or the password variable is empty then you want to put into the status field fill out all of the form data else if the email and the password do have values then you can go ahead and process the form with Ajax so the login button you just want to give the style display:none or visibility:hidden property whichever way you want to go about hiding or disabling your login button while ajax is processing then for the status element you want to put in the inner HTML please wait because that's when the Ajax mechanism is about to occur so we run our Ajax mechanism you can see down here we're sending two variables E and P which represent email and password to the PHP script in our case we're posting to login dot PHP just like we did with sign up that PHP and I'll say it again like I said it before you can take this PHP code that processes this Ajax and put it in an external separated file if you want but since this login dot PHP is the only page that is going to need this PHP script I see it makes good sense to just have it live directly in this script okay so when the data comes back from PHP we're going to check to see if the Ajax response text is equal to login failed and we want to put in the status div that login was unsuccessful please try again and you want the login button to come back so whatever way you made the login button go away or be disabled or be invisible you want to bring it back at that point so if the Ajax response text is not equal to log in failed else you're going to run window location and just assure the you to their profile page which is user dot PHP with a URL variable of you it's going to be equal to this user's name so I made the PHP script spit back just if the login is successful just spit back the users name and that's what you put on the end of this variable that way the user will be ushered to their particular profile upon successful login and you can you can send them to any page you want with any variables you want attached you can handle that any way you like so that's all of the Java Script and now all we have to do is explain the PHP which is very very simple so in this page login dot PHP I opted to check their sessions see if they would happen to be logged in so maybe a logged in user might just type in login dot PHP even if you don't have any links to it they might just type in login dot PHP and then they'll navigate to your login page and they're already logged in and that doesn't make any sense because they're already logged in why would they want to be on that page so I just assure them away to their user profile now here we have another PHP block and this one I wrote a little comment that says Ajax calls this login code to execute so when people come to the login dot PHP page this code isn't going to execute unless they fill out the form and press login then this code executes an ajax calls it to run let's open that up and we say if is set the posted variable of E which is email then we'll know that the form is being submit and we can execute this code so the first thing we do is connect to the database using our include file for the database connection then we gather the post and data into local variables and sanitize them so we get e scooped up into local variable by using MySQL I real escape string function on it to sanitize the posted e variable and put the password variable all you do is simply hash that using whatever encryption method that you decided upon so this line makes it match what's in the database so we can do a comparison then you get the user IP address and I'm going to be talking to you guys about how you can use the user IP address for security reasons so just leave this line in here for now even though we might not have the mechanism for security in place we'll put it in place later and I'll discuss it with you guys later but you want to keep updating the user's IP address in the database every time they log in now they form data error handling which we do in JavaScript but we're going to also do it in PHP in case anybody bypasses our JavaScript so we just check to see if the email and password actually have values if they don't we just echo login failed and exit else if the values are there you can go ahead and check for a match in the database so you set up your SQL syntax that reads select ID username and password from the users table where email equals this person's email address so we're selecting their ID the username and password where the email matches with the users typing in then we run that MySQL I query here we put it in a variable called query so then we can my SQL I fetch that row from the database with the users ID username and password then we put those row variables here into local variables here let's say database ID database username and database password string you can see we're just accessing the row as an array and getting the little indexes that we need we know the first thing we selected was the ID so that'll be 0 the second thing was username that'll be 1 third thing was password that'll be 2 in the array and that's how you can access those fields and then you run an if condition that says if the password that the user is typing in if that is not equal to they're stored hash for their password then you want to echo login failed because what they're typing in is their password in the login form does not match what you have on file else if their password that they're typing in does match the password that you have on file for that user that has that email address then you run this code which essentially logs them in first you create their sessions and cookie files session and cookie files files that get created on the user's browser software within the users browser software well really it's stored on the user's computer in their temp folder somewhere but the browser whatever software they're using to browse the web with that's what actually creates the cookie or the session file now sessions are short-lived files only while the users browser is open for instance if we only made sessions here and we didn't set any cookies down here every time the user close their browser came back the next day they'd have to log back in but if you set cookies your site automatically just remembers them and in mice in my login form I'm not going to put a box that says remember me checkbox I'm just going to my site it's just going to automatically remember them but if you want to be on the up-and-up you can put the little checkbox that says remember me that way the user has the option of telling your system to go ahead and create cookie files and then finally you update their IP address and their last login fields in the database so you update users set IP and last login field for the last login field you can just specify now in SQL syntax which will give you the current timestamp where user name is equal to this particular unique user in the database and we put limit 1 because we only want to update one row in the database and then we here we actually run that query and we echo back to the login form Ajax the database username and then we exit ok so once the username is echoed back you exit that script and then JavaScript Ajax takes back over right here and you window.location the user to their profile and that is all there is to login dot PHP ok now let's quickly discuss logout dot PHP first thing you do is session start that way you can work with your session variables within the script and remember session start has to go the first line the very top of your file it's recommended that you have session start be the really the first line within your PHP if you're going to use session start for instance you shouldn't have extra pH blocks or whitespace up above this should be just like that you open your PHP block and you put session start directly you really don't want to have session start anywhere else because it could lead to problems for you now here we set the session data to an empty array then we expire their cookie files and if you guys want to really learn about set cookie and how to set your sessions you just check the PHP manual anytime you see in any of these scripts that we're working with any of these PHP built-in functions like set cookie session destroy' header you see all these functions you just go to that PHP manual that I showed you earlier in this video and put in the search box the function name and you can learn in depth all about it read all the user contributed notes and you can really master PHP that way by using the PHP manual directly that way you get a PHP coding straight from the horse's mouth and you're now listening to other douchebags like me so basically what we're doing is setting the cookie to a time in the past five days ago that will expire their cookie then you're going to destroy the session variables by running the session destroy' function then the last thing and this is optional you can just double check to see if their sessions exist anymore you say if is set session username then you can header them to message that PHP within message of ever logout failed or you can just echo to the page here logout failed but this really should never occur you'll have this else condition header them to the home page of your website upon successful log out you can header them to any URL that you want upon successful logout and that's all there is to logout dot PHP okay now let's quickly discuss the code at work inside of check login status dot PHP check login status dot PHP is a file that you are going to make live inside of your PHP includes folder on the server it's not going to be in your public HTML it will be with all of your include file so you put it with your PHP include files in that folder now basically the whole gist of this whole file is to have a module that you start session in the top line always of every script that you're going to use it in so that means if you are going to include this file check login status into any other scripts it has to be the first line you include it into the first line of any other scripts because you want to run session start first line in all of your scripts then you include the database connection so what this means is files that include this file at the very top of them they would not require connection to the database because it's already connected and they won't require session start because it's already in place here so you be careful if you're going to include check login status type PHP into any pages which we are into user dot PHP so if you're going to include this into user PHP you certainly don't want to have a connection to your database in that and you don't want to have session start at the top because you're already starting the session by including check login status into user dot PHP in the very top then we'll simply initialize some variables and down here in the bottom is where we are checking to see if they're logged in or not so basically what you want to do is check to see if their session variables are set and if they are you're going to run this code now maybe they're opening their browser and coming back a week later to your site and their session variables aren't set yet but their cookies are set then you want to run this code to see else if their cookies are set you run this code here so if their sessions are set you run this code if their cookies are set you run this code but most of the time when they're browsing your site their sessions will be set and this first if condition will be picked up in this code will run and only really when they come back from not visiting the site for a day or a week with this else condition run I'll explain this function evaluate logged user in just a second okay so if their session variables are set we are going to take their session variables and sanitize them because people can change what their session files say they can change their cookie files basically using certain software since people can put in any kind of strings they want into these session files you don't ever want to query your database without sanitizing session or cookie data since the end user can manipulate all of that data you want to make sure it's sanitized before it touches your database at all so that's why we're using preg replace here to make sure that the users ID only has and only is allowed numbers in the value you want to check that log username only has letters and numbers and the same thing for the logged password that it only has letters and numbers since we're using md5 because md5 hash only makes a letter and number hash if you're using a more complex hash and salting method you would want to make sure that you allow for instance the dollar sign or if you're going to have dot underscores in your strings make sure you allow those by putting those symbols in but mine is not it's only going to have a per case lowercase letters and numbers in it so basically you're taking the session data if their sessions are available if your system recognizes that their session files are available you're taking those session file data and you're putting it into local PHP variables called log ID log username log password then after you get those into local variables you're going to run the function called eval logs user up here and you're going to feed it for variables the database connection variable the person's ID the person's user name and the person's password those are all for going to be sent to the eval logged user function right here and that is all of that section for if the session variables are already set and you can see that I have user okay as the name of the variable that holds the value of the output of this function and up here we initialize that with a value of false so if it's a visitor that's not a member of your site that's not logged in or anything basically they'll always be user ok false okay so since we're running this function here eval logged user let me explain that real quick before I explain the cookie section so in eval logs user what you want to do is set up your SQL syntax to read select IP address from the users table where the ID equals this user's session ID and where the username equals this user's session username and where the password equals this user's session password and where the activated equals one so basically that's how you make the match logic you want to see if their session data matches something on file that way you're double checking to make sure that user is who they say they are so as long as you make sure your site doesn't allow cross-site scripting attacks you're fine and the system I'm going to give you all the way through the end of production there's nowhere in that system in this system that I'm producing here that someone can put in malicious JavaScript code and conduct cross-site scripting attacks furthermore there will be nowhere in this system where somebody can perform my SQL injection so we're safe so this eval log user function runs really just as a double check mechanism - just to make sure that nobody's playing around trying to impersonate somebody else by simply opening their cookie files and changing the values to some other user's name or something like that that any kid can do that any kid can open up their cookie files and change the value of them so if everything is a nice match then you're going to run that query and get the number rose result from that using the MySQL num rows function and you can evaluate that num rows result and check to see if it is greater than 0 then you can return true that means if everything matched up and the user is authenticated then you can return true to the line that called this function to run and the line that called this function to run is right here user okay so basically user okay if everything is works out and the user is authenticated this is going to have a value of true otherwise if they're not it's going to remain with a value of false okay so let me collapse this backup and all we have to do is show you now the part of the code that runs only if the user is maybe coming back from a week later not visiting your site for a couple days over and their sessions have expired because they close their browser but they still have their cookie files that are letting is letting our site remember them this code runs in that case so you take their cookie file because their sessions aren't set yet and you set their sessions according to what the cookie file data is and you can go ahead and sanitize that as you do it then you make those local variables that we need log ID login surname log password out of their session data so for instance if you wanted to put the user's name whoever is logged in you want to show them their own name on a page you can just echo this variable to a page and you don't have to echo all this so that's why I just put it into local PHP variables or if you want to ever evaluate their user ID or the username you can just use these local variables and you can make yours really short if you want mine are only long local variable names because I want you guys to really understand what it represents but you can have this say hy e if you want or be something really short small it doesn't matter just as long as you remember what it's for so after we get their sessions established again then we can run that eval logs user function again to give us a true value here if the user authenticates okay and then finally in the bottom here you say if the user okay is equal to true that means they're authenticated you want to update their last login time field because if they're coming back from two weeks later they haven't visited your site in two weeks you want to make sure that your system updates that last until your other users know when was the last time he had come back or she had come back to visit site because if you don't update that it'll say their last login is whatever 30 days ago whatever but they might have been at your site five days ago so that's why it would help you if you want to keep track of that pettite and that's basically it that's that whole file and like I said this file is mainly to give us a module that's going to start session and include a database connection into all of our pages because almost every single page on your social networking website you're going to have to evaluate the viewer that is viewing the page you will see if they are logged in or not and you want to also know if they authenticate and match in the database with all their credentials so that's what this file will be used for anytime you want to see if the user really authenticated they are who they say they are supposed to be you can just check this user ok variable in any of your pages you just say if user ok equals true then I can do this secure action ok the last file that you're getting today is user dot PHP and this file we're going to be enhancing a little bit more later on right now I just wanted to give it to you so that way when you your users log in or when you're testing when you login successfully you're navigated straight to this page but basically down in the HTML there's nothing special going on I'm just for now just outputting certain variables or information about the member that I gathered out of the database and we gather it out of the database up here in the top so the first thing we do when users dot PHP is we require once you could also use include ones right there you just have to make sure that that page is where you think it is so we're including once from the PHP includes folder the file called check login status dot PHP so you know exactly what all the code that we're including here does because it's sitting right here I just explained it all that code is going to be included into your users PHP script alright so after that you can initialize any variables that might echo on to the page because in some servers if you don't initialize the variables so they're not set at the top if you try and echo them down in the HTML you could get an error that's why it's handy to just initialize any variables that might echo to the page so we're just establishing them with default values then we make sure that the get username variable is set and then we sanitize it so if I go to my profile user dot PHP u equals Adam the user profile page knows what profile to display or what person to display from the database by this variable right here that's the variable that you're scooping up to key value pair the key is you and the values atom or whatever the username might be so you say if it said get that username variable then you want to sanitize it and put it in a local variable called you else if that get variable is not even set you want to echo them or just echo some error message to them or header them away to the home page like I did here because that means somebody's tampering with the URL they're removing variables that are supposed to be in the URL string so this really this code would never execute unless somebody's being a doofus then you're going to use that variable that incoming get variable to select the member from the user's table so your SQL syntax reads select all from users where username equals you variable and activate it equals one and I just added activated equals one just to make sure if this was 0 and they haven't activated yet you don't want this page to render and their profile to display to other people to you if you do you could just remove that but if you don't leave that in place so you're selecting all of their information from the users table where the user name matches up and you actually execute that query here and put it in a variable called the user query now we're going to make sure that the user exists in the table so we can run MySQL num rows on that user query and we get a variable called num rows that we can evaluate here in this if condition we say if the number rose is less than 1 that means they don't exist so you can echo out that user does not exist or is not yet activated press back and exit the script or you can header them somewhere and handle that anyway if you like so if they actually do exist we're going to check to see if the viewer is the account owner because if the viewer who's looking at the page is the actual account owner that owns that page you can do things like give them buttons that nobody else would see and other logic along those lines so we create a variable called is owner and we initialize it with a default value of no then we can simply run a condition that says if the you get variable coming into the page is equal to log user name and you know that's their session username and user ok is equal to true then you can say is owner equals yes and then any other time down through this page where you want to say if is owner equals yes echo this special button just for him you know what I'm saying if it is owner equals yes giving a special thing because this guy owns this profile now here we can finally fetch all of the user data out of their row so you're going to run a while loop over the MySQL fetch array function and that gets packed into a variable called row you can see in the MySQL I fetch array function I'm feeding it two parameters the first parameter is the user query the second parameter is how I want this fetched array to be accessed so you can set it to be accessed as an associative array which I have here or you can set it up to be an indexed array where this would be 0 and numbers down all through here instead of the actual label or title of the field but I think it's just easier for beginners to grasp what they're selecting out of the database when they can see the actual title of the field in the database so you select the ID their gender their country their user level sign up without anything in in the whole table that you want to select and you put it into local variables here and their join date and the last session date I'm just using the string F time function and the string to time function to make those to make those date strings in the database display the way I want them to on the page like a human readable version of that date and the last thing within the while loop after we scooped up all that data out from all those fields we say if the gender equals F we're going to change sex from its default male up here to female because in that case your user would be a female and you don't want to have that continue to say male want to change that to female so that way down in the page where you echo there's so their gender you get the right output okay so what you're doing here is you're getting these things ready to be displayed or you can process them in your code whatever but at that point they're ready to use we can echo them to the page or do whatever we want with them and that's it like I said there's a lot more that's going to be happening on this page because they have to get options to adjust their profile it's going to have to be buttons so when other members come and they view this person's profile they have a little link to friend with that person or block that person things like that so this page is definitely going to get some more we're not done with this one okay so in this video we covered the login the logout understanding sessions and cookies and how to establish them to keep the user alive even if they close their browser come back a week later and establishing the profile page with the initial logic that it needs to display all kinds of different users and I'll see you guys in part 8
Info
Channel: Adam Khoury
Views: 196,177
Rating: undefined out of 5
Keywords: php login tutorial, php sign up, log in tutorial, user accounts, php mysql login, social network development, php tutorial, validate user, mysql tutorial, php website tutorial, how to build a social network, website development tutorial, user authentication, learn web design, learn, howto, php script, script, education, program, web, development, design, online, free, lesson, teacher, student, educational, school, class, adam khoury
Id: gav4HmZ8xe8
Channel Id: undefined
Length: 38min 51sec (2331 seconds)
Published: Sun Jan 27 2013
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.